Skip to content

Instantly share code, notes, and snippets.

@NakHalal
Last active December 21, 2025 08:22
Show Gist options
  • Select an option

  • Save NakHalal/ffa321613d1de9fd0ec1cc79bb6e1b0c to your computer and use it in GitHub Desktop.

Select an option

Save NakHalal/ffa321613d1de9fd0ec1cc79bb6e1b0c to your computer and use it in GitHub Desktop.
NanoGPT CCR Custom Transformer

NanoGPT Transformer

JavaScript

A powerful transformer that enables seamless integration between Claude Code and NanoGPT API, converting reasoning formats and handling model-specific quirks.

📋 Prerequisites

⚠️ Important: You must have Claude Code Router (CCR) installed before using this transformer.

Required:

✨ Features

  • 🧠 Reasoning-to-Thinking Conversion: Automatically converts NanoGPT's reasoning format to Claude Code's thinking format
  • 📊 Token Usage Tracking: Injects stream_options: { include_usage: true } for accurate token counting
  • 🔄 Model Switching Support: Handles max_tokens=1 requests with fake response generation
  • 🌊 Stream Processing: Supports streaming responses with reasoning-to-thinking conversion
  • ⚡ Performance Optimized: Buffer management for streaming responses

🚀 Quick Start

Installation

The NanoGPT transformer is a single JavaScript file that integrates with Claude Code Router.

Step 1: Verify CCR Installation

First, ensure Claude Code Router is installed:

# Check if CCR is installed
ccr --version

# If not installed, install it first:
# Using npm
npm install -g @musistudio/claude-code-router

# Or using pnpm (recommended)
pnpm add -g @musistudio/claude-code-router

Step 2: Download the Transformer

Option A: Using curl (Recommended)

# Create the plugins directory if it doesn't exist
mkdir -p ~/.claude-code-router/plugins

# Download the minified version (smaller file size)
curl -o ~/.claude-code-router/plugins/nanogpt.js https://gist.githubusercontent.com/NakHalal/ffa321613d1de9fd0ec1cc79bb6e1b0c/raw/nanogpt.minified.js

Option B: Manual Download

Save the file to: ~/.claude-code-router/plugins/nanogpt.js

Step 3: Configure NanoGPT Provider

Create or edit your ~/.claude-code-router/config.json:

{
  "Providers": [
    {
      "name": "nanogpt",
      "api_base_url": "https://nano-gpt.com/api/v1/chat/completions",
      "api_key": "your-nanogpt-api-key-here",
      "models": [
        "z-ai/glm-4.6",
        "deepseek-chat",
        "qwen/qwen3-coder",
        "moonshotai/kimi-k2-thinking"
      ],
      "transformer": {
        "use": ["nanogpt"]
      }
    }
  ],
  "Router": {
    "default": "z-ai/glm-4.6",
    "think": "moonshotai/kimi-k2-thinking"
  }
}

⚠️ Important: Replace your-nanogpt-api-key-here with your actual NanoGPT API key.

Step 4: Start CCR

# Start the router
ccr start

# Verify it's running
ccr status

Step 5: Test the Setup

# Start interactive Claude Code session
ccr code

# Then type your prompt when prompted, for example:
# Hello, can you help me?

That's it! The NanoGPT transformer will now automatically handle:

  • ✅ Reasoning-to-thinking conversion
  • ✅ Token usage tracking
  • ✅ Model switching support
  • ✅ Stream processing

🔄 Model Switching

You can easily switch between different NanoGPT models using the /model command in Claude Code. This allows you to leverage different model capabilities based on your specific needs.

Basic Model Switching

To switch to a specific model, use the format:

/model <provider>,<model-id>

⚠️ Common Mistake: Don't forget the provider name! Incorrect: /model glm-4.6 ✅ Correct: /model nanogpt,z-ai/glm-4.6

Example: Switching to GLM-4.6

To switch to the GLM-4.6 model from NanoGPT:

/model nanogpt,z-ai/glm-4.6

Where:

  • nanogpt is the provider name (configured in your config.json)
  • z-ai/glm-4.6 is the model ID from NanoGPT

Finding Available Models

You can view all available NanoGPT models at: NanoGPT API Page

Popular Model Examples

# Switch to GLM-4.6 with online search capabilities
/model nanogpt,z-ai/glm-4.6:online

# Switch to DeepSeek chat model
/model nanogpt,deepseek-chat:memory

# Switch to a thinking/reasoning model
/model nanogpt,deepseek-ai/DeepSeek-V3.1:thinking

# Switch to a coding-focused model
/model nanogpt,qwen/qwen3-coder

# Switch to a multimodal model with vision
/model nanogpt,meta-llama/llama-3.2-90b-vision-instruct

Model Capability Matrix

Model Best For Thinking Tool Calling Vision Notes
z-ai/glm-4.6 General use Most reliable
z-ai/glm-4.6:thinking General reasoning GLM-4.6 with thinking
moonshotai/kimi-k2-thinking Complex reasoning ⚠️ Tool calling issues
minimax/minimax-01 Long context Good reasoning, poor tools
qwen/qwen3-coder Coding Good alternative
deepseek-ai/DeepSeek-V3.1:thinking Advanced reasoning Included in subscription

Tips for Model Switching

  1. Check model availability: Not all models may be available with your current subscription
  2. Consider model capabilities: Choose models based on your task requirements
  3. Monitor token usage: Different models have different token limits and pricing
  4. Test compatibility: Some features may work differently across models
  5. Use the right syntax: Always include provider name: /model nanogpt,model-id
  6. Verify after switching: Use /model without arguments to check current model

🏗️ Architecture

How It Works

The NanoGPT Transformer acts as a bridge between Claude Code and NanoGPT API, handling three key transformations:

  1. Request Enhancement: Adds stream options and prepares requests for NanoGPT
  2. Response Processing: Converts NanoGPT responses back to Claude Code format
  3. Reasoning Conversion: Transforms reasoning content to thinking format

Component Overview

flowchart TD
    A[Claude Code] --> R[Claude Code Router]
    R --> B[NanoGPT Transformer]
    B --> C[NanoGPT API]
    
    A1[Thinking mode] --> A
    A2[Tool calls] --> A
    A3[Token tracking] --> A
    
    R1[Routing] --> R
    R2[Provider selection] --> R
    R3[Streaming/SSE] --> R
    
    B1[Stream options] --> B
    B2[Format conversion] --> B
    B3[Error handling] --> B
    
    C1[Reasoning] --> C
    C2[200+ models] --> C
    C3[Streaming] --> C
Loading

Core Components

  • 🔄 NanoGPTProductionTransformer: Main class handling all transformations
  • 📝 Stream Processing: Real-time conversion of streaming responses
  • 🎭 Fake Response Generator: Handles model switching edge cases
  • 🧠 Reasoning Converter: Transforms reasoning to thinking format

📋 Supported Models

The NanoGPT Transformer supports various models across different categories:

🧠 Thinking Models

Models with reasoning capabilities converted to thinking format:

  • deepseek-ai/DeepSeek-V3.1:thinking
  • z-ai/glm-4.6:thinking
  • GLM-4.5-Air-Iceblink:thinking
  • moonshotai/kimi-k2-thinking
  • nousresearch/hermes-4-405b:thinking
  • Qwen/Qwen3-235B-A22B-Thinking-2507
  • And more...

💻 Coding Models

Models optimized for programming:

  • Qwen/Qwen2.5-Coder-32B-Instruct
  • qwen/qwen3-coder
  • KAT-Coder-Air-V1
  • KAT-Coder-Exp-72B-1010

🌐 Multimodal Models

Models with vision capabilities:

  • meta-llama/llama-3.2-90b-vision-instruct
  • Qwen/Qwen3-VL-235B-A22B-Instruct
  • phi-4-multimodal-instruct

🔍 Reasoning Models

Models with specialized reasoning:

  • deepseek-reasoner
  • deepseek-r1
  • QwQ-32B-ArliAI-RpR-v1
  • qwq-32b

See the complete list at https://nano-gpt.com/api.

⚙️ Configuration

Basic Configuration

The NanoGPT transformer is configured through the provider configuration in your ~/.claude-code-router/config.json:

{
  "Providers": [
    {
      "name": "nanogpt",
      "api_base_url": "https://nano-gpt.com/api/v1/chat/completions",
      "api_key": "your-api-key-here",
      "models": [
        "deepseek-chat",
        "qwen/qwen3-coder",
        "deepseek-ai/DeepSeek-V3.1:thinking",
        "moonshotai/kimi-k2-thinking"
      ],
      "transformer": {
        "use": ["nanogpt"]
      }
    }
  ]
}

Advanced Configuration

Multiple Endpoints

For different model types, you can configure multiple providers:

{
  "Providers": [
    {
      "name": "nanogpt",
      "api_base_url": "https://nano-gpt.com/api/v1/chat/completions",
      "api_key": "your-api-key-here",
      "models": ["z-ai/glm-4.6", "deepseek-chat"],
      "transformer": { "use": ["nanogpt"] }
    },
    {
      "name": "nanogpt-legacy",
      "api_base_url": "https://nano-gpt.com/api/v1legacy/chat/completions",
      "api_key": "your-api-key-here",
      "models": ["moonshotai/kimi-k2-thinking"],
      "transformer": { "use": ["nanogpt"] }
    }
  ]
}

Transformer Path Configuration

Relative Path (Recommended):

{
  "transformer": {
    "use": ["nanogpt"]
  }
}

Absolute Path:

{
  "transformer": {
    "use": ["/path/to/your/nanogpt.js"]
  }
}

Complete Transformer Configuration

For full control over all transformer features, use the complete configuration:

{
  "Providers": [
    {
      "name": "nanogpt",
      "api_base_url": "https://nano-gpt.com/api/v1/chat/completions",
      "api_key": "your-api-key-here",
      "models": [
        "deepseek-chat",
        "qwen/qwen3-coder",
        "deepseek-ai/DeepSeek-V3.1:thinking",
        "moonshotai/kimi-k2-thinking"
      ],
      "transformer": {
        "use": ["nanogpt"]
      }
    }
  ],
  "transformers": [
    {
      "options": {
        "enable": true,
        "enableStreamOptions": true,
        "enableReasoningToThinking": true,
        "enableFakeResponse": true,
        "sanitizeToolSyntaxInReasoning": false,
        "sanitizeToolSyntaxInContent": false,
        "enableForceReasoning": false,
        "temperature": 0.1,
        "max_tokens": -99,
        "top_p": 0.95,
        "frequency_penalty": 0,
        "presence_penalty": 0
        // Optional parameters (only included when explicitly set by user):
        // "parallel_tool_calls": true,
        // "top_k": 40,
        // "repetition_penalty": 1.15,
        // "reasoning_effort": "none",
        // "cache_control": {
        //   "enabled": false,
        //   "ttl": "5m"
        // }
      },
      "path": "Your\\Path\\To\\The\\Transformer\\File\\nanogpt.js"
    }
  ]
}

Configuration Options Explained:

  • enable (boolean): Master switch for the transformer (default: true)
  • enableStreamOptions (boolean): Inject stream_options: { include_usage: true } for token tracking (default: true)
  • enableReasoningToThinking (boolean): Convert NanoGPT reasoning format to Claude Code thinking format (default: true)
  • enableFakeResponse (boolean): Generate fake responses for max_tokens=1 requests (model switching) (default: true)
  • sanitizeToolSyntaxInReasoning (boolean): Remove pseudo-tool syntax from reasoning content (default: false)
  • sanitizeToolSyntaxInContent (boolean): Remove pseudo-tool syntax from regular content (default: false)
  • enableForceReasoning (boolean): Inject reasoning prompts for non-reasoning models (default: false)
  • temperature (number): Sampling temperature (0-2, default: 0.1)
  • max_tokens (number): Maximum tokens to generate (default: -99). Set to -99 to omit this parameter from the request, letting Claude Code control token limits
  • top_p (number): Nucleus sampling parameter (0-1, default: 0.95)
  • frequency_penalty (number): Reduce token repetition (-2 to 2, default: 0)
  • presence_penalty (number): Reduce topic repetition (-2 to 2, default: 0)
  • parallel_tool_calls (boolean): Enable parallel tool execution (default: omitted). Only included in API requests when explicitly set by user
  • top_k (number): Limit vocabulary to top K tokens (default: omitted). Only included in API requests when explicitly set by user
  • repetition_penalty (number): Alternative repetition control (default: omitted). Only included in API requests when explicitly set by user
  • reasoning_effort (string): Controls computational effort for reasoning (default: omitted)
    • Valid values: "none" (disables reasoning), "minimal" (~10% of tokens), "low" (~20% of tokens), "medium" (~50% of tokens), "high" (~80% of tokens)
    • Higher values result in more thorough reasoning but slower responses and higher costs
    • Only applicable to reasoning-capable models
    • Only included in API requests when explicitly set by user
    • Claude Code Integration: When Claude Code Thinking is ON, the transformer uses the configured reasoning_effort from options. When Thinking is OFF, it automatically sets reasoning_effort to "none". If neither is configured, the parameter is omitted.
  • cache_control (object): Cache control settings with enabled and ttl properties (default: omitted). Only included in API requests when explicitly set by user

Router Configuration

Configure models based on their capabilities:

{
  "Router": {
    "default": "z-ai/glm-4.6",
    "think": "moonshotai/kimi-k2-thinking", 
    "longContext": "minimax/minimax-01",
    "webSearch": "z-ai/glm-4.6:online",
    "image": "qwen3-vl-235b-a22b-instruct-original",
    "background": "z-ai/glm-4.6"
  }
}

Transformer Features

The NanoGPT transformer automatically handles:

  • 🧠 Reasoning Conversion: Converts NanoGPT reasoning format to Claude Code thinking format
  • 📊 Token Tracking: Injects stream_options: { include_usage: true } for accurate token counting
  • 🔄 Model Switching: Handles max_tokens=1 requests for seamless model switching
  • 🎭 Fake Responses: Generates proper responses for models that don't handle max_tokens=1, especially when changing model
  • 🔗 Endpoint Compatibility: Supports both v1 and v1legacy NanoGPT API endpoints

🔧 API Reference

NanoGPTProductionTransformer Class

Constructor

new NanoGPTProductionTransformer(options)

Parameters:

  • options.enable (boolean): Enable/disable transformer (default: true)

Methods

transformRequestIn(request)

Transform incoming request before sending to NanoGPT API.

Parameters:

  • request (Object): Original request object

Returns:

  • Object: Modified request with stream_options

Example:

const transformer = new NanoGPTProductionTransformer({ enable: true });
const modifiedRequest = await transformer.transformRequestIn({
    model: "deepseek-chat",
    messages: [{ role: "user", content: "Hello" }],
    stream: true
});
// Result: { model: "deepseek-chat", messages: [...], stream: true, stream_options: { include_usage: true } }
transformResponseOut(response)

Transform outgoing response from NanoGPT API to Claude Code format.

Parameters:

  • response (Response): Original response from NanoGPT

Returns:

  • Response: Transformed response with thinking format

Utility Functions

generateId()

Generate realistic OpenAI-style ID for fake responses.

Returns:

  • string: ID in format chatcmpl-XXXXXXXXXXXXXXaaaa

createFakeResponse(model)

Create fake response for max_tokens=1 workaround.

Parameters:

  • model (string): Model name untuk response

Returns:

  • Object: Fake response object

processStreamLine(line, controller, encoder, context)

Process single SSE stream line with reasoning-to-thinking conversion.

Parameters:

  • line (string): Line to process
  • controller (TransformStreamDefaultController): Stream controller
  • encoder (TextEncoder): Text encoder
  • context (Object): Stream state context

🔧 Troubleshooting

Common Issues

🤖 Model Not Responding to max_tokens=1

Problem: Model doesn't respond correctly during model switching.

Solution: The transformer automatically detects this and generates a fake response. Check logs for:

[INFO] Model changing detected (max_tokens=1), returning fake response as workaround

🧠 Thinking Content Not Appearing

Problem: Reasoning content doesn't appear in Claude Code.

Solution: Ensure your model supports thinking or reasoning and is configured correctly:

{
  "Router": {
    "think": "moonshotai/kimi-k2-thinking"
  }
}

📊 Token Usage Not Tracked

Problem: Status line doesn't show token usage.

Solution: The transformer automatically adds stream_options: { include_usage: true }. If tokens aren't showing, check if your model returns usage data.

🔌 API Connection Issues

Problem: Cannot connect to NanoGPT API.

Solution: Verify your configuration:

{
  "api_base_url": "https://nano-gpt.com/api/v1/chat/completions",
  "api_key": "your-valid-api-key",
}

Model-Specific Issues

Kimi K2 Thinking - Tool Calling Problems

Problem: Tool calls are embedded in reasoning delta instead of tool call delta (model-specific issue).

Solution: Use GLM-4.6 for tasks requiring tool calling:

/model nanogpt,z-ai/glm-4.6

MiniMax-M2 - Poor Tool Support

Problem: Model doesn't respond to tool calls properly.

Solution: Use for reasoning-only tasks or switch to DeepSeek:

/model nanogpt,deepseek-chat

GLM-4.6 - No Thinking Mode

Problem: Thinking content doesn't appear with GLM-4.6.

Solution: GLM-4.6 doesn't support thinking. Use a thinking model instead:

/model nanogpt,moonshotai/kimi-k2-thinking

Performance Optimization

Buffer Management

Transformer uses 1MB buffer limit to prevent memory issues:

// Safety buffer limit (1MB)
if (buffer.length > 1e6) {
    const lines = buffer.split('\n');
    buffer = lines.pop() || "";
    // Process lines
}

Stream Processing

Stream processing optimization with TextDecoder/TextEncoder:

const decoder = new TextDecoder();
const encoder = new TextEncoder();

// Process chunk by chunk
const chunk = decoder.decode(value, { stream: true });

Memory Cleanup

Automatic cleanup for stream resources:

finally {
    try {
        reader.releaseLock();
    } catch (error) {
        // Ignore lock release errors
    }
    controller.close();
}

🎯 Model-Specific Guidance

🏆 Recommended Models by Use Case

General Purpose (Most Reliable)

  • GLM-4.6 (z-ai/glm-4.6)
    • ✅ Excellent tool calling
    • ✅ Stable performance
    • ✅ Good reasoning
    • ❌ No thinking mode

General Purpose with Thinking

  • GLM-4.6 Thinking (z-ai/glm-4.6:thinking)
    • ✅ Excellent tool calling
    • ✅ Stable performance
    • ✅ Good reasoning with thinking mode
    • ✅ Included in subscription

Complex Reasoning

  • Kimi K2 Thinking (moonshotai/kimi-k2-thinking)
    • ✅ Advanced reasoning
    • ✅ Deep analysis
    • ⚠️ Tool calling issues
    • ✅ Good for complex problems

Coding & Development

  • Qwen3 Coder (qwen/qwen3-coder)
    • ✅ Excellent code generation
    • ✅ Multiple language support
    • ✅ Good debugging
    • ❌ No thinking mode

Advanced Reasoning

  • DeepSeek V3.1 Thinking (deepseek-ai/DeepSeek-V3.1:thinking)
    • ✅ Advanced reasoning
    • ✅ Tool calling support
    • ✅ Multimodal capabilities
    • ✅ Included in subscription

Model Selection Guide

⚠️ Disclaimer: This guide is for reference only and not tested at all (LLM generated).

Task Recommended Model Alternative
General chat z-ai/glm-4.6 deepseek-chat
Complex reasoning moonshotai/kimi-k2-thinking z-ai/glm-4.6:thinking or deepseek-ai/DeepSeek-V3.1:thinking or MiniMax-M2
Code generation qwen/qwen3-coder KAT-Coder-Air-V1
Tool calling z-ai/glm-4.6 deepseek-chat
Long context minimax/minimax-01 Qwen/Qwen3-235B-A22B-Thinking-2507
Vision tasks meta-llama/llama-3.2-90b-vision-instruct Qwen/Qwen3-VL-235B-A22B-Instruct

🚀 Performance

Optimizations Built-in

  • 🧠 Memory Management: 1MB buffer limits prevent memory issues
  • ⚡ Stream Processing: Efficient TextDecoder/TextEncoder usage
  • 🔄 Automatic Cleanup: Proper resource management and error handling
  • 📊 Token Tracking: Minimal overhead usage tracking

❓ FAQ

Why use CCR instead of direct Claude Code?
  • Cost savings: NanoGPT models are often cheaper than Claude
  • Model variety: Access to 219 specialized models for $8/month (as of Dec 2, 2025)
  • Flexibility: Switch models based on task requirements
  • Privacy: Use local or alternative API providers
How do I know which model to choose?

Consider your task:

  • General chat: GLM-4.6 (most reliable)
  • Complex reasoning: Kimi K2 Thinking or DeepSeek V3.1 Thinking
  • Coding: Qwen3 Coder
  • Tool calling: GLM-4.6 or DeepSeek Chat
Why isn't thinking working?
  1. Check if model supports thinking (see model list)
  2. Verify Router.think configuration
  3. Use /model to switch to a thinking model
  4. Check logs for errors
Known Issue: Model changing with `/model` doesn't work

Problem: User types /model glm-4.6 and it doesn't work.

Solution: You MUST include the provider name. The correct syntax is:

/model <provider>,<model-id>

Examples:

  • ❌ Wrong: /model glm-4.6
  • ❌ Wrong: /model z-ai/glm-4.6
  • ✅ Correct: /model nanogpt,z-ai/glm-4.6
  • ✅ Correct: /model nanogpt,z-ai/glm-4.6:thinking

To check current model: Type /model without any arguments.

Can I use multiple providers?

Yes! Configure multiple providers in config.json:

{
  "Providers": [
    {"name": "nanogpt", ...},
    {"name": "openai", ...}
  ]
}
Where can I get help?

For bug reports, questions, or discussions, visit the Discord channel: NanoGPT Discord

📝 Changelog

Click to expand changelog

[0.1.4] - 2025-12-21

Added

  • Comprehensive Error Handling: Added error interception for common HTTP status codes with user-friendly error messages

    • 401 Unauthorized: "Session required. Your API key is invalid or expired."
    • 403 Forbidden: "Insufficient permissions. You don't have access to this resource."
    • 404 Not Found: "The requested resource was not found."
    • 409 Conflict: "Resource conflict detected. This could be due to duplicate creation or wrong state."
    • 422 Invalid Input: "Validation failed. Please check your request parameters and format."
    • 429 Rate Limited: "Too many requests. Please wait and try again later."
    • 500 Internal Error: "The server encountered an unexpected error."
    • Works for both streaming (SSE) and non-streaming (JSON) responses
    • Returns proper fake responses with error messages instead of letting errors propagate
  • Global Fetch Interceptor: Added monkey-patching of global fetch to intercept errors before the router throws

    • Handles specific NanoGPT API error signatures (e.g., rate_limit_exceeded, invalid_api_key, insufficient_permissions)
    • Prevents crashes from authentication failures and rate limits
    • Generates appropriate streaming or non-streaming responses based on request type

Changed

  • Error Response Format: Errors are now returned as valid chat completion responses
    • Error messages are prefixed with emoji indicators (⚠️) for visibility
    • Streaming responses include proper SSE format with message_start, content_delta, and message_stop events
    • Non-streaming responses follow standard OpenAI chat completion format

Improved

  • Documentation: Updated JSDoc documentation to include error handling information
    • Added "Error Handling" section in Purpose documentation
    • Added new troubleshooting entries for error-related issues
    • Documented supported HTTP status codes and their user-friendly messages

[0.1.3] - 2025-12-08

Changed

  • max_tokens Default Behavior: Changed max_tokens default from -1 to -99
    • Previous behavior (-1): Kept the value unchanged, passing Claude Code's -1 to the API
    • New behavior (-99): Omits max_tokens entirely, letting Claude Code's value pass through untouched
    • This change improves compatibility by not interfering with Claude Code's token management
    • Users who explicitly set max_tokens in config will still have their value applied

Added

  • UltraThink Documentation: Added documentation about the UltraThink feature
    • When users type "UltraThink" in their prompt, Claude Code automatically toggles Thinking mode ON
    • This is a built-in Claude Code feature that triggers extended thinking/reasoning for complex tasks
    • The transformer receives the reasoning parameter with enabled: true and applies the configured effort level

Improved

  • Code Cleanup: Simplified utility functions and removed debug logging
    • Removed unused paramName parameter from getRandomInRange() function
    • Removed unused paramName parameter from resolveParameterValue() function signature
    • Removed debug console.log statements for cleaner production code
    • Simplified max_tokens handling logic by removing the special case for -1

[0.1.2] - 2025-12-08

Changed

  • Reasoning Parameter Handling: Now ALWAYS sets reasoning and reasoning_effort parameters in API requests
    • When CC Thinking is ON: Sets reasoning.enabled=true, reasoning.exclude=false with configured effort level
    • When CC Thinking is OFF: Sets reasoning.enabled=false, reasoning.exclude=true, reasoning_effort="none"
    • This ensures consistent behavior for both reasoning and non-reasoning models

Fixed

  • transformResponseOut Bug: Fixed critical bug where responseToProcess variable was referenced before being declared
    • Added missing let responseToProcess = response; declaration at the start of the method
    • Removed duplicate variable declaration let transformedResponse = responseToProcess;
    • This fixes the "responseToProcess is not defined" error during response processing

Improved

  • Force Reasoning Logic: Simplified CC Thinking state tracking
    • Now uses ccThinkingEnabled boolean to track CC Thinking state consistently
    • Force reasoning is only applied when CC Thinking is ON AND model is not a reasoning model
    • Removed redundant ccThinkingDisabled check in force reasoning injection logic

[0.1.1] - 2025-12-08

Changed

  • Parameter Inclusion Strategy: Major shift from "include all parameters by default" to "minimal by default" approach

    • Now only includes 5 core parameters in API requests by default: temperature, max_tokens, top_p, frequency_penalty, presence_penalty
    • All other parameters (parallel_tool_calls, top_k, repetition_penalty, reasoning_effort, cache_control, extra) are only included if explicitly set by user
    • This reduces request size and prevents unintended parameter transmission
  • Default Parameter Values: Changed to minimal approach - only 5 core parameters included by default

    • temperature: 0.1 (included by default)
    • max_tokens: -1 (included by default)
    • top_p: 0.95 (included by default)
    • frequency_penalty: 0 (included by default)
    • presence_penalty: 0 (included by default)
    • parallel_tool_calls, top_k, repetition_penalty: Now omitted by default (only included when explicitly set)

Added

  • Explicit Parameter Documentation: Clear distinction between "Default Parameters" and "Optional Parameters"
    • Default Parameters: Always included in requests (5 core parameters)
    • Optional Parameters: Only included when explicitly set by user
    • Each parameter now clearly documents its inclusion behavior

Enhanced

  • Parameter Control Philosophy: Better alignment with API best practices
    • Users now have explicit control over which optional parameters are sent
    • Reduces risk of unintended parameter effects
    • More transparent request composition
    • Better debugging capabilities with explicit parameter tracking

[0.1.0] - 2025-12-07

Changed

  • Reasoning Effort Default: Changed reasoning_effort default value from "low" to "none"
    • Now defaults to disabled reasoning for faster responses by default
    • Users must explicitly configure reasoning effort to enable reasoning capabilities
    • Maintains backward compatibility for existing configurations that explicitly set reasoning_effort

Added

  • Claude Code Reasoning Integration: Enhanced integration with Claude Code's reasoning format
    • Treats Claude Code's reasoning parameter as a simple on/off switch
    • Implements precedence logic: user explicit > Claude Code toggle > configuration default
    • When Claude Code Thinking is ON: uses configured reasoning_effort value
    • When Claude Code Thinking is OFF: automatically sets reasoning_effort to "none"
    • Creates both reasoning and reasoning_effort parameters for maximum NanoGPT compatibility

Enhanced

  • Reasoning Parameter Handling: Improved reasoning parameter resolution and validation
    • Added comprehensive reasoning source tracking for debugging
    • Enhanced error handling with detailed source information in validation messages
    • Improved fallback logic from "low" to "none" for invalid reasoning_effort values
    • Added support for user override of reasoning_effort in requests

[0.0.9] - 2025-12-07

Added

  • Reasoning Effort Parameter: Added reasoning_effort parameter to control computational effort for reasoning in NanoGPT models
    • Supports 5 levels: "none" (disables reasoning), "minimal" (~10% of tokens), "low" (~20% of tokens), "medium" (~50% of tokens), "high" (~80% of tokens)
    • Higher values result in more thorough reasoning but slower responses and higher costs
    • Only applicable to reasoning-capable models
    • Includes validation with fallback to "none" for invalid values
    • Comprehensive documentation with usage examples for different scenarios

Changed

  • Enhanced Documentation: Expanded configuration documentation with reasoning effort examples
    • Added dedicated "Reasoning Parameters" section in configuration docs
    • Included practical examples for high reasoning, fast responses, and disabled reasoning scenarios
    • Updated JSDoc comments to document the new reasoning_effort parameter

[0.0.8] - 2025-12-05

Fixed

  • max_tokens=-99 Omission Bug: Fixed bug where max_tokens=-99 was not being properly omitted when set in configuration
    • Added shouldOmitParameter(this.max_tokens) check to handle config-level -99 values
    • Previously only checked for -99 in request but not in configuration
    • Now correctly omits max_tokens when set to -99 in either request or config

[0.0.7] - 2025-12-05

Changed

  • max_tokens Preservation Logic: Enhanced to preserve both max_tokens=1 (model switching) and max_tokens=-1 (Claude Code self-configuration) values
    • Added shouldPreserveMaxTokens variable for cleaner code logic
    • Now respects when caller allows Claude Code to configure itself (-1)
    • Maintains backward compatibility with model switching behavior

Fixed

  • Documentation Update: Corrected version header from v0.0.6 (Unpublished) to v0.0.7
  • JSDoc Comments: Updated parameter documentation to reflect max_tokens preservation behavior

[0.0.6] - 2025-12-04

Added

  • Range Parameter Support: All numeric parameters now support range specification using "min-max" format for dynamic randomization
    • Generates random values within specified ranges for each request while maintaining backward compatibility
    • Supports negative numbers and floating-point values with proper validation
    • Example: "temperature": "0.1-0.8" generates random temperature between 0.1 and 0.8 for each request
  • New Sampling Parameters: Extended parameter support for advanced model control:
    • parallel_tool_calls (default: omitted, supports: "true-false" for boolean randomization)
    • top_k (default: omitted, range: 1-100, supports: "20-80" for range randomization)
    • repetition_penalty (default: omitted, range: 0.1-2.0, supports: "0.8-1.2" for range randomization)
  • Range Resolution Functions: Comprehensive utilities for parameter range handling:
    • parseRange() - Parses range strings and returns min/max values with validation
    • getRandomInRange() - Generates random numbers within specified ranges with debug logging
    • resolveParameterValue() - Resolves parameters to concrete values (exact or range-based)
  • Default Parameter Values: Minimal approach with only 5 core parameters included by default:
    • temperature: 0.1 - More deterministic responses for better reliability
    • max_tokens: -1 - Let Claude Code or model determine token limit
    • top_p: 0.95 - Balanced diversity for natural language output
    • frequency_penalty: 0 - Neutral setting (no token-level repetition control)
    • presence_penalty: 0 - Neutral setting (no topic-level repetition control)
    • Optional parameters (parallel_tool_calls, top_k, repetition_penalty) are omitted unless explicitly set

Changed

  • Enhanced Constructor: Added range configuration storage and resolution for all sampling parameters
  • Improved Request Processing: All sampling parameters now support both exact values and range strings
  • Better Parameter Validation: Added comprehensive range parsing with error handling and fallbacks
  • Expanded Documentation: Added detailed examples and usage patterns for range parameters

Fixed

  • Parameter Type Handling: Proper boolean conversion for parallel_tool_calls parameter
  • Integer Parameter Rounding: Ensured max_tokens and top_k are properly rounded to integers
  • Range Configuration Storage: Added _rangeConfigs object to store parsed range information

[0.0.5] - 2025-12-04

Fixed

  • max_tokens Override Issue: Removed preservation of max_tokens=-1 (Claude Code self-configuration) to prevent conflicts with configured max_tokens values
  • Debug Logging: Simplified max_tokens debug logic to only handle model switching case (max_tokens=1)

Changed

  • max_tokens Handling: Now only preserves original max_tokens when it's 1 (model switching), allowing configured max_tokens to override Claude Code self-configuration (-1) values
  • Configuration Consistency: Ensures configured max_tokens takes precedence except for Claude Code's model switching edge case

[0.0.4] - 2025-12-02

Added

  • Force Reasoning Feature: Added enableForceReasoning option to inject reasoning prompts for non-reasoning models
  • Reasoning Models Detection: Comprehensive REASONING_MODELS list with 40+ reasoning models including:
    • DeepSeek Reasoning Models (deepseek-reasoner, deepseek-v3.2:thinking, etc.)
    • Moonshot Reasoning Models (kimi-k2-thinking)
    • GLM Reasoning Models (GLM-4.5-Air-Iceblink:thinking, glm-4.6:thinking, etc.)
    • Hermes Reasoning Models (Hermes-4-70B:thinking, etc.)
    • Qwen Reasoning Models (Qwen3-235B-A22B-Thinking-2507, qwq-32b, etc.)
    • Other specialized reasoning models
  • Model Detection Logic: isReasoningModel() function with exact matching and fallback heuristics
  • Force Reasoning Prompt: Standardized prompt template with <reasoning_content> tags for structured reasoning output
  • State Machine Parser: processForceReasoningContent() function for handling streaming responses with reasoning tags
  • Enhanced Message Injection: Smart prompt injection for system messages, user messages, and tool responses
  • Force Reasoning Constants: FORCE_REASONING_START_TAG and FORCE_REASONING_END_TAG for consistent parsing

Changed

  • Enhanced max_tokens Handling: Preserve original max_tokens values of 1 (model switching) and -1 (Claude Code self-configuration) instead of overriding with configured default
  • Improved Request Processing: Added force reasoning application tracking with forceReasoningApplied flag
  • Enhanced Response Processing: Added force reasoning support to both streaming and non-streaming response handlers
  • Better Debug Logging: Added comprehensive logging for force reasoning application and model detection

Fixed

  • Model Detection Edge Cases: Added non-reasoning variants list to prevent false positives in model detection
  • Streaming State Management: Proper handling of partial tag matches across stream chunks
  • Content Preservation: Ensured original content is preserved when force reasoning is not applied

[0.0.3] - 2025-11-28

Added

  • Sampling Parameters: Full OpenAI-compatible parameter support:
    • temperature (0-2, default: 0.7) - Controls randomness in output
    • max_tokens (default: 4000) - Maximum tokens to generate
    • top_p (0-1, default: 1) - Nucleus sampling parameter
    • frequency_penalty (-2 to 2, default: 0) - Reduces token repetition
    • presence_penalty (-2 to 2, default: 0) - Reduces topic repetition
  • Cache Control: cache_control configuration with enabled/disabled states and TTL support
  • Pseudo-Tool Syntax Cleanup: Comprehensive utilities for handling malformed tool markers
  • Content Sanitization Options: Clean pseudo-tool syntax from reasoning and regular content
  • Enhanced Streaming Processing: Pseudo-tool block detection and content dropping

Changed

  • Enhanced Request Transformation: Added sampling parameter injection with configurable defaults
  • Improved Stream Processing: Added pseudo-tool syntax handling to streaming pipeline
  • Better Content Handling: Intelligent content preservation when removing tool syntax

Fixed

  • Tool Syntax Leakage: Prevented pseudo-tool markers from appearing in user-facing content
  • Content Loss: Added fallback messages when content becomes empty after tool cleanup
  • Stream Buffer Management: Improved handling of tool block boundaries in streaming responses

[0.0.2] - 2025-11-26

Added

  • Configurable Feature Toggles: All major features now have independent controls:
    • enableStreamOptions (default: true) - Control stream_options injection
    • enableReasoningToThinking (default: true) - Control reasoning-to-thinking conversion
    • enableFakeResponse (default: true) - Control max_tokens=1 workaround
  • Comprehensive Documentation: Detailed configuration explanations with purpose, rationale, and risk assessments
  • Usage Examples: Practical code examples for different configuration scenarios
  • Enhanced Logging: Feature status logging on transformer initialization

Changed

  • Modular Feature Design: Converted hardcoded features to configurable options
  • Improved Function Signatures: Added feature flags to response handling functions
  • Enhanced Constructor: Added feature toggle initialization with safe defaults

Fixed

  • Backward Compatibility: Maintained default behavior for existing configurations
  • Feature Independence: Ensured features can be enabled/disabled without affecting others

[0.0.1] - 2025-11-25

Added

  • Initial NanoGPT API Transformer: Complete transformer for NanoGPT API compatibility
  • Reasoning-to-Thinking Conversion: Transforms NanoGPT reasoning/reasoning_content fields to Claude Code thinking format
  • Stream Options Injection: Automatically adds stream_options: { include_usage: true } to all requests
  • Fake Response Generation: Workaround for models that don't handle max_tokens=1 correctly (Claude Code model switching)
  • Dual Endpoint Support: Compatible with both v1 and v1legacy NanoGPT endpoint formats
  • Streaming and Non-Streaming Support: Handles both response types with proper transformation
  • Token Count Integration: Enables Claude Code statusline to display accurate token usage
  • Thinking Mode Display: Makes model reasoning process visible in Claude Code UI
  • OpenAI-Compatible IDs: Generates realistic response IDs for fake responses
  • Comprehensive Error Handling: Graceful fallbacks for parsing errors and edge cases

Security

  • Input Validation: Safe JSON parsing with error recovery
  • Content Sanitization: Proper handling of malformed streaming data
  • Memory Protection: 1MB buffer limit to prevent memory exhaustion

📄 License

This project is licensed under the GPLv3 License - see the LICENSE file for details.


⭐ If you find this transformer helpful, consider giving it a star!

Changelog

All notable changes to NanoGPT Transformer will be documented in this file.

[0.1.4] - 2025-12-21

Added

  • Comprehensive Error Handling: Added error interception for common HTTP status codes with user-friendly error messages

    • 401 Unauthorized: "Session required. Your API key is invalid or expired."
    • 403 Forbidden: "Insufficient permissions. You don't have access to this resource."
    • 404 Not Found: "The requested resource was not found."
    • 409 Conflict: "Resource conflict detected. This could be due to duplicate creation or wrong state."
    • 422 Invalid Input: "Validation failed. Please check your request parameters and format."
    • 429 Rate Limited: "Too many requests. Please wait and try again later."
    • 500 Internal Error: "The server encountered an unexpected error."
    • Works for both streaming (SSE) and non-streaming (JSON) responses
    • Returns proper fake responses with error messages instead of letting errors propagate
  • Global Fetch Interceptor: Added monkey-patching of global fetch to intercept errors before the router throws

    • Handles specific NanoGPT API error signatures (e.g., rate_limit_exceeded, invalid_api_key, insufficient_permissions)
    • Prevents crashes from authentication failures and rate limits
    • Generates appropriate streaming or non-streaming responses based on request type

Changed

  • Error Response Format: Errors are now returned as valid chat completion responses
    • Error messages are prefixed with emoji indicators (⚠️) for visibility
    • Streaming responses include proper SSE format with message_start, content_delta, and message_stop events
    • Non-streaming responses follow standard OpenAI chat completion format

Improved

  • Documentation: Updated JSDoc documentation to include error handling information
    • Added "Error Handling" section in Purpose documentation
    • Added new troubleshooting entries for error-related issues
    • Documented supported HTTP status codes and their user-friendly messages

[0.1.3] - 2025-12-08

Changed

  • max_tokens Default Behavior: Changed max_tokens default from -1 to -99
    • Previous behavior (-1): Kept the value unchanged, passing Claude Code's -1 to the API
    • New behavior (-99): Omits max_tokens entirely, letting Claude Code's value pass through untouched
    • This change improves compatibility by not interfering with Claude Code's token management
    • Users who explicitly set max_tokens in config will still have their value applied

Added

  • UltraThink Documentation: Added documentation about the UltraThink feature
    • When users type "UltraThink" in their prompt, Claude Code automatically toggles Thinking mode ON
    • This is a built-in Claude Code feature that triggers extended thinking/reasoning for complex tasks
    • The transformer receives the reasoning parameter with enabled: true and applies the configured effort level

Improved

  • Code Cleanup: Simplified utility functions and removed debug logging
    • Removed unused paramName parameter from getRandomInRange() function
    • Removed unused paramName parameter from resolveParameterValue() function signature
    • Removed debug console.log statements for cleaner production code
    • Simplified max_tokens handling logic by removing the special case for -1

[0.1.2] - 2025-12-08

Changed

  • Reasoning Parameter Handling: Now ALWAYS sets reasoning and reasoning_effort parameters in API requests
    • When CC Thinking is ON: Sets reasoning.enabled=true, reasoning.exclude=false with configured effort level
    • When CC Thinking is OFF: Sets reasoning.enabled=false, reasoning.exclude=true, reasoning_effort="none"
    • This ensures consistent behavior for both reasoning and non-reasoning models

Fixed

  • transformResponseOut Bug: Fixed critical bug where responseToProcess variable was referenced before being declared
    • Added missing let responseToProcess = response; declaration at the start of the method
    • Removed duplicate variable declaration let transformedResponse = responseToProcess;
    • This fixes the "responseToProcess is not defined" error during response processing

Improved

  • Force Reasoning Logic: Simplified CC Thinking state tracking
    • Now uses ccThinkingEnabled boolean to track CC Thinking state consistently
    • Force reasoning is only applied when CC Thinking is ON AND model is not a reasoning model
    • Removed redundant ccThinkingDisabled check in force reasoning injection logic

[0.1.1] - 2025-12-08

Changed

  • Parameter Inclusion Strategy: Major shift from "include all parameters by default" to "minimal by default" approach

    • Now only includes 5 core parameters in API requests by default: temperature, max_tokens, top_p, frequency_penalty, presence_penalty
    • All other parameters (parallel_tool_calls, top_k, repetition_penalty, reasoning_effort, cache_control, extra) are only included if explicitly set by user
    • This reduces request size and prevents unintended parameter transmission
  • Default Parameter Values: Significant changes to optimize for different use cases

    • temperature: 0.2 → 0.1 (more deterministic responses)
    • max_tokens: 8192 → -1 (allows Claude Code to control token limits)
    • top_p: 0.6 → 0.95 (more permissive sampling)
    • frequency_penalty: 0.1 → 0 (no repetition penalty by default)
    • presence_penalty: 0.0 → 0 (consistent with previous)

Added

  • Explicit Parameter Documentation: Clear distinction between "Default Parameters" and "Optional Parameters"
    • Default Parameters: Always included in requests (5 core parameters)
    • Optional Parameters: Only included when explicitly set by user
    • Each parameter now clearly documents its inclusion behavior

Enhanced

  • Parameter Control Philosophy: Better alignment with API best practices
    • Users now have explicit control over which optional parameters are sent
    • Reduces risk of unintended parameter effects
    • More transparent request composition
    • Better debugging capabilities with explicit parameter tracking

[0.1.0] - 2025-12-07

Changed

  • Reasoning Effort Default: Changed reasoning_effort default value from "low" to "none"
    • Now defaults to disabled reasoning for faster responses by default
    • Users must explicitly configure reasoning effort to enable reasoning capabilities
    • Maintains backward compatibility for existing configurations that explicitly set reasoning_effort

Added

  • Claude Code Reasoning Integration: Enhanced integration with Claude Code's reasoning format
    • Treats Claude Code's reasoning parameter as a simple on/off switch
    • Implements precedence logic: user explicit > Claude Code toggle > configuration default
    • When Claude Code Thinking is ON: uses configured reasoning_effort value
    • When Claude Code Thinking is OFF: automatically sets reasoning_effort to "none"
    • Creates both reasoning and reasoning_effort parameters for maximum NanoGPT compatibility

Enhanced

  • Reasoning Parameter Handling: Improved reasoning parameter resolution and validation
    • Added comprehensive reasoning source tracking for debugging
    • Enhanced error handling with detailed source information in validation messages
    • Improved fallback logic from "low" to "none" for invalid reasoning_effort values
    • Added support for user override of reasoning_effort in requests

[0.0.9] - 2025-12-07

Added

  • Reasoning Effort Parameter: Added reasoning_effort parameter to control computational effort for reasoning in NanoGPT models
    • Supports 5 levels: "none" (disables reasoning), "minimal" (~10% of tokens), "low" (~20% of tokens, default), "medium" (~50% of tokens), "high" (~80% of tokens)
    • Higher values result in more thorough reasoning but slower responses and higher costs
    • Only applicable to reasoning-capable models
    • Includes validation with fallback to "low" for invalid values
    • Comprehensive documentation with usage examples for different scenarios

Changed

  • Enhanced Documentation: Expanded configuration documentation with reasoning effort examples
    • Added dedicated "Reasoning Parameters" section in configuration docs
    • Included practical examples for high reasoning, fast responses, and disabled reasoning scenarios
    • Updated JSDoc comments to document the new reasoning_effort parameter

[0.0.8] - 2025-12-05

Fixed

  • max_tokens=-99 Omission Bug: Fixed bug where max_tokens=-99 was not being properly omitted when set in configuration
    • Added shouldOmitParameter(this.max_tokens) check to handle config-level -99 values
    • Previously only checked for -99 in request but not in configuration
    • Now correctly omits max_tokens when set to -99 in either request or config

[0.0.7] - 2025-12-05

Changed

  • max_tokens Preservation Logic: Enhanced to preserve both max_tokens=1 (model switching) and max_tokens=-1 (Claude Code self-configuration) values
    • Added shouldPreserveMaxTokens variable for cleaner code logic
    • Now respects when caller allows Claude Code to configure itself (-1)
    • Maintains backward compatibility with model switching behavior

Fixed

  • Documentation Update: Corrected version header from v0.0.6 (Unpublished) to v0.0.7
  • JSDoc Comments: Updated parameter documentation to reflect max_tokens preservation behavior

[0.0.6] - 2025-12-04

Added

  • Range Parameter Support: All numeric parameters now support range specification using "min-max" format for dynamic randomization
    • Generates random values within specified ranges for each request while maintaining backward compatibility
    • Supports negative numbers and floating-point values with proper validation
    • Example: "temperature": "0.1-0.8" generates random temperature between 0.1 and 0.8 for each request
  • New Sampling Parameters: Extended parameter support for advanced model control:
    • parallel_tool_calls (default: true, supports: "true-false" for boolean randomization)
    • top_k (default: 40, range: 1-100, supports: "20-80" for range randomization)
    • repetition_penalty (default: 1.15, range: 0.1-2.0, supports: "0.8-1.2" for range randomization)
  • Range Resolution Functions: Comprehensive utilities for parameter range handling:
    • parseRange() - Parses range strings and returns min/max values with validation
    • getRandomInRange() - Generates random numbers within specified ranges with debug logging
    • resolveParameterValue() - Resolves parameters to concrete values (exact or range-based)
  • Optimized Default Values: Research-backed parameter defaults optimized for code generation:
    • temperature: 0.2 - Optimal for code generation based on research findings
    • top_p: 0.6 - Balances creativity and correctness for systematic testing
    • frequency_penalty: 0.1 - Prevents token repetition while maintaining code flow
    • presence_penalty: 0.0 - Minimal penalty to avoid breaking syntax patterns
    • top_k: 40 - Balances exploration and exploitation for code tokens
    • repetition_penalty: 1.15 - Optimal for preventing structural repetition in code

Changed

  • Enhanced Constructor: Added range configuration storage and resolution for all sampling parameters
  • Improved Request Processing: All sampling parameters now support both exact values and range strings
  • Better Parameter Validation: Added comprehensive range parsing with error handling and fallbacks
  • Expanded Documentation: Added detailed examples and usage patterns for range parameters

Fixed

  • Parameter Type Handling: Proper boolean conversion for parallel_tool_calls parameter
  • Integer Parameter Rounding: Ensured max_tokens and top_k are properly rounded to integers
  • Range Configuration Storage: Added _rangeConfigs object to store parsed range information

[0.0.5] - 2025-12-04

Fixed

  • max_tokens Override Issue: Removed preservation of max_tokens=-1 (Claude Code self-configuration) to prevent conflicts with configured max_tokens values
  • Debug Logging: Simplified max_tokens debug logic to only handle model switching case (max_tokens=1)

Changed

  • max_tokens Handling: Now only preserves original max_tokens when it's 1 (model switching), allowing configured max_tokens to override Claude Code self-configuration (-1) values
  • Configuration Consistency: Ensures configured max_tokens takes precedence except for Claude Code's model switching edge case

[0.0.4] - 2025-12-02

Added

  • Force Reasoning Feature: Added enableForceReasoning option to inject reasoning prompts for non-reasoning models
  • Reasoning Models Detection: Comprehensive REASONING_MODELS list with 40+ reasoning models including:
    • DeepSeek Reasoning Models (deepseek-reasoner, deepseek-v3.2:thinking, etc.)
    • Moonshot Reasoning Models (kimi-k2-thinking)
    • GLM Reasoning Models (GLM-4.5-Air-Iceblink:thinking, glm-4.6:thinking, etc.)
    • Hermes Reasoning Models (Hermes-4-70B:thinking, etc.)
    • Qwen Reasoning Models (Qwen3-235B-A22B-Thinking-2507, qwq-32b, etc.)
    • Other specialized reasoning models
  • Model Detection Logic: isReasoningModel() function with exact matching and fallback heuristics
  • Force Reasoning Prompt: Standardized prompt template with <reasoning_content> tags for structured reasoning output
  • State Machine Parser: processForceReasoningContent() function for handling streaming responses with reasoning tags
  • Enhanced Message Injection: Smart prompt injection for system messages, user messages, and tool responses
  • Force Reasoning Constants: FORCE_REASONING_START_TAG and FORCE_REASONING_END_TAG for consistent parsing

Changed

  • Enhanced max_tokens Handling: Preserve original max_tokens values of 1 (model switching) and -1 (Claude Code self-configuration) instead of overriding with configured default
  • Improved Request Processing: Added force reasoning application tracking with forceReasoningApplied flag
  • Enhanced Response Processing: Added force reasoning support to both streaming and non-streaming response handlers
  • Better Debug Logging: Added comprehensive logging for force reasoning application and model detection

Fixed

  • Model Detection Edge Cases: Added non-reasoning variants list to prevent false positives in model detection
  • Streaming State Management: Proper handling of partial tag matches across stream chunks
  • Content Preservation: Ensured original content is preserved when force reasoning is not applied

[0.0.3] - 2025-11-28

Added

  • Sampling Parameters: Full OpenAI-compatible parameter support:
    • temperature (0-2, default: 0.7) - Controls randomness in output
    • max_tokens (default: 4000) - Maximum tokens to generate
    • top_p (0-1, default: 1) - Nucleus sampling parameter
    • frequency_penalty (-2 to 2, default: 0) - Reduces token repetition
    • presence_penalty (-2 to 2, default: 0) - Reduces topic repetition
  • Cache Control: cache_control configuration with enabled/disabled states and TTL support
  • Pseudo-Tool Syntax Cleanup: Comprehensive utilities for handling malformed tool markers:
    • stripPseudoToolBlocks() - Removes complete tool call sections
    • stripPseudoToolSyntax() - Removes individual tool markers
    • Support for Kimi/NanoGPT tool markers (<|tool_call_begin|>, <|tool_call_end|>, etc.)
  • Content Sanitization Options:
    • sanitizeToolSyntaxInReasoning - Clean pseudo-tool syntax from reasoning content
    • sanitizeToolSyntaxInContent - Clean pseudo-tool syntax from regular content
  • Enhanced Streaming Processing:
    • Pseudo-tool block detection and content dropping
    • Fallback content generation when tool blocks are removed
    • State tracking for inside/outside tool blocks

Changed

  • Enhanced Request Transformation: Added sampling parameter injection with configurable defaults
  • Improved Stream Processing: Added pseudo-tool syntax handling to streaming pipeline
  • Better Content Handling: Intelligent content preservation when removing tool syntax
  • Expanded Documentation: Added comprehensive chaos test cases for pseudo-tool scenarios

Fixed

  • Tool Syntax Leakage: Prevented pseudo-tool markers from appearing in user-facing content
  • Content Loss: Added fallback messages when content becomes empty after tool cleanup
  • Stream Buffer Management: Improved handling of tool block boundaries in streaming responses

[0.0.2] - 2025-11-26

Added

  • Configurable Feature Toggles: All major features now have independent controls:
    • enableStreamOptions (default: true) - Control stream_options injection
    • enableReasoningToThinking (default: true) - Control reasoning-to-thinking conversion
    • enableFakeResponse (default: true) - Control max_tokens=1 workaround
  • Comprehensive Documentation: Detailed configuration explanations with:
    • Purpose and rationale for each feature
    • Risk assessments for disabling features
    • Safety guidelines for configuration changes
  • Usage Examples: Practical code examples for different configuration scenarios
  • Enhanced Logging: Feature status logging on transformer initialization

Changed

  • Modular Feature Design: Converted hardcoded features to configurable options
  • Improved Function Signatures: Added feature flags to response handling functions
  • Enhanced Constructor: Added feature toggle initialization with safe defaults
  • Better Error Handling: Graceful degradation when features are disabled

Fixed

  • Backward Compatibility: Maintained default behavior for existing configurations
  • Feature Independence: Ensured features can be enabled/disabled without affecting others

[0.0.1] - 2025-11-25

Added

  • Initial NanoGPT API Transformer: Complete transformer for NanoGPT API compatibility
  • Reasoning-to-Thinking Conversion: Transforms NanoGPT reasoning/reasoning_content fields to Claude Code thinking format
  • Stream Options Injection: Automatically adds stream_options: { include_usage: true } to all requests
  • Fake Response Generation: Workaround for models that don't handle max_tokens=1 correctly (Claude Code model switching)
  • Dual Endpoint Support: Compatible with both v1 and v1legacy NanoGPT endpoint formats
  • Streaming and Non-Streaming Support: Handles both response types with proper transformation
  • Token Count Integration: Enables Claude Code statusline to display accurate token usage
  • Thinking Mode Display: Makes model reasoning process visible in Claude Code UI
  • OpenAI-Compatible IDs: Generates realistic response IDs for fake responses
  • Comprehensive Error Handling: Graceful fallbacks for parsing errors and edge cases

Security

  • Input Validation: Safe JSON parsing with error recovery
  • Content Sanitization: Proper handling of malformed streaming data
  • Memory Protection: 1MB buffer limit to prevent memory exhaustion
{
"LOG": false,
"LOG_LEVEL": "debug",
"CLAUDE_PATH": "",
"HOST": "127.0.0.1",
"PORT": 3456,
"APIKEY": "",
"API_TIMEOUT_MS": "600000",
"PROXY_URL": "",
"NON_INTERACTIVE_MODE": false,
"transformers": [
{
"options": {
"enable": true,
"enableStreamOptions": true,
"enableReasoningToThinking": true,
"enableFakeResponse": true,
"sanitizeToolSyntaxInReasoning": false,
"sanitizeToolSyntaxInContent": false,
"enableForceReasoning": true,
"temperature": -99,
"max_tokens": -1,
"top_p": -99,
"frequency_penalty": -99,
"presence_penalty": -99,
"parallel_tool_calls": false,
"top_k": -99,
"repetition_penalty": -99,
"cache_control": {
"enabled": false,
"ttl": "5m"
}
},
"path": "$HOME/.claude-code-router/plugins/nanogpt.js"
}
],
"Providers": [
{
"name": "nanogpt",
"api_base_url": "https://nano-gpt.com/api/v1/chat/completions",
"api_key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"models": [
"deepseek/deepseek-v3.2-speciale",
"mistralai/ministral-14b-instruct-2512",
"mistralai/mistral-large-3-675b-instruct-2512",
"deepseek/deepseek-v3.2",
"deepseek/deepseek-v3.2:thinking",
"Doctor-Shotgun/MS3.2-24B-Magnum-Diamond",
"moonshotai/kimi-k2-thinking",
"KAT-Coder-Air-V1",
"KAT-Coder-Exp-72B-1010",
"KAT-Coder-Pro-V1",
"MiniMax-M2",
"inclusionai/ling-1t",
"GLM-4.5-Air-Iceblink",
"GLM-4.5-Air-Iceblink:thinking",
"GLM-4.5-Air-Steam-v1",
"GLM-4.5-Air-Steam-v1:thinking",
"z-ai/glm-4.6",
"z-ai/glm-4.6:thinking",
"EVA-UNIT-01/EVA-LLaMA-3.33-70B-v0.1",
"EVA-UNIT-01/EVA-Qwen2.5-72B-v0.2",
"soob3123/GrayLine-Qwen3-8B",
"moonshotai/Kimi-K2-Instruct-0905",
"Ling-Flash-2.0",
"meta-llama/llama-3.2-90b-vision-instruct",
"Magistral-Small-2506",
"microsoft/MAI-DS-R1-FP8",
"qwen3-vl-235b-a22b-instruct-original",
"NousResearch/Hermes-4-70B:thinking",
"Qwen/Qwen3-235B-A22B-Thinking-2507",
"Qwen/Qwen3-Next-80B-A3B-Instruct",
"tngtech/DeepSeek-TNG-R1T2-Chimera",
"meta-llama/llama-4-maverick",
"meta-llama/llama-4-scout",
"meituan-longcat/LongCat-Flash-Chat-FP8",
"deepseek-ai/DeepSeek-R1-0528-Qwen3-8B",
"nousresearch/hermes-4-405b",
"qwen3-vl-235b-a22b-thinking",
"Alibaba-NLP/Tongyi-DeepResearch-30B-A3B",
"pamanseau/OpenReasoning-Nemotron-32B",
"TheDrummer/Cydonia-24B-v4.1",
"Gemma-3-27B-Big-Tiger-v3",
"Gemma-3-27B-Nidum-Uncensored",
"Meta-Llama-3-1-405B-Instruct-FP8",
"Llama-3.3-70B-ArliAI-RPMax-v2",
"huihui-ai/Llama-3.3-70B-Instruct-abliterated",
"Gryphe/MythoMax-L2-13b",
"nvidia/Llama-3.3-Nemotron-Super-49B-v1",
"nvidia/Llama-3_3-Nemotron-Super-49B-v1_5",
"openai/gpt-oss-120b",
"openai/gpt-oss-20b",
"qwen3-coder-30b-a3b-instruct",
"tngtech/DeepSeek-R1T-Chimera",
"deepseek-ai/DeepSeek-V3.1-Terminus",
"abacusai/Dracarys-72B-Instruct",
"mistralai/Devstral-Small-2505",
"agentica-org/DeepCoder-14B-Preview",
"deepseek-ai/DeepSeek-V3.1",
"EVA-UNIT-01/EVA-LLaMA-3.33-70B-v0.0",
"EVA-UNIT-01/EVA-Qwen2.5-32B-v0.2",
"LLM360/K2-Think",
"failspy/Meta-Llama-3-70B-Instruct-abliterated-v3.5",
"Llama-3.3-70B-Magnum-v4-SE-Cirrus-x1-SLERP",
"Llama-3.3-70B-MiraiFanfare",
"Llama-3.3-70B-Progenitor-V3.3",
"phi-4-mini-instruct",
"phi-4-multimodal-instruct",
"shisa-ai/shisa-v2-llama3.3-70b",
"Qwen/Qwen3-235B-A22B-Instruct-2507",
"TheDrummer/Cydonia-24B-v4",
"Qwen/Qwen3-235B-A22B",
"Gemma-3-27B-it-Abliterated",
"Gemma-3-27B-ArliAI-RPMax-v3",
"nousresearch/hermes-4-70b",
"nvidia/Llama-3.1-Nemotron-Ultra-253B-v1",
"Qwen/Qwen2.5-Coder-32B-Instruct",
"qwen/qwen-2.5-72b-instruct",
"soob3123/amoral-gemma3-27B-v2",
"deepcogito/cogito-v1-preview-qwen-32B",
"NousResearch/DeepHermes-3-Mistral-24B-Preview",
"qwen25-vl-72b-instruct",
"deepseek-chat-cheaper",
"zai-org/GLM-4.5",
"zai-org/GLM-4.5-Air",
"THUDM/GLM-Z1-32B-0414",
"THUDM/GLM-Z1-Rumination-32B-0414",
"moonshotai/Kimi-Dev-72B",
"chutesai/Mistral-Small-3.2-24B-Instruct-2506",
"mistral-small-31-24b-instruct",
"nvidia/Llama-3.1-Nemotron-70B-Instruct-HF",
"qwq-32b",
"Salesforce/Llama-xLAM-2-70b-fc-r",
"soob3123/Veiled-Calla-12B",
"qvq-max",
"thedrummer/skyfall-36b-v2",
"deepseek-chat",
"cognitivecomputations/dolphin-2.9.2-qwen2-72b",
"meta-llama/llama-3.3-70b-instruct",
"qwen/qwq-32b-preview",
"qwen/qwen3-30b-a3b",
"venice-uncensored",
"LatitudeGames/Wayfarer-Large-70B-Llama-3.3",
"qwen3-30b-a3b-instruct-2507",
"QwQ-32B-ArliAI-RpR-v1",
"TheDrummer/Cydonia-24B-v2",
"qwen/qwen3-coder",
"sarvan-medium",
"ReadyArt/The-Omega-Abomination-L-70B-v1.0",
"deepseek-ai/DeepSeek-R1-0528",
"moonshotai/kimi-k2-instruct",
"moonshotai/kimi-k2-instruct-0711",
"nousresearch/hermes-4-405b:thinking",
"deepseek-r1",
"minimax/minimax-01",
"qwen/qwen3-32b",
"qwen/qwen3-14b",
"Sao10K/L3-8B-Stheno-v3.2",
"deepseek-ai/deepseek-v3.2-exp",
"deepseek-ai/deepseek-v3.2-exp-thinking",
"Steelskull/L3.3-MS-Nevoria-70b",
"Steelskull/L3.3-Nevoria-R1-70b",
"Steelskull/L3.3-Electra-R1-70b",
"NeverSleep/Lumimaid-v0.2-70B",
"anthracite-org/magnum-v4-72b",
"Qwen/Qwen3-8B",
"deepseek-ai/DeepSeek-V3.1:thinking",
"deepseek-ai/DeepSeek-V3.1-Terminus:thinking",
"deepseek-v3-0324",
"baseten/Kimi-K2-Instruct-FP4",
"zai-org/GLM-4.5:thinking",
"zai-org/GLM-4.5-Air:thinking",
"GalrionSoftworks/MN-LooseCannon-12B-v1",
"meta-llama/llama-3.1-8b-instruct",
"undi95/remm-slerp-l2-13b",
"mistralai/mistral-tiny",
"mistralai/mistral-saba",
"mistralai/mistral-7b-instruct",
"mlabonne/NeuralDaredevil-8B-abliterated",
"huihui-ai/Llama-3.1-Nemotron-70B-Instruct-HF-abliterated",
"anthracite-org/magnum-v2-72b",
"Steelskull/L3.3-Damascus-R1",
"mistralai/Mistral-Nemo-Instruct-2407",
"deepseek-reasoner",
"Envoid/Llama-3.05-NT-Storybreaker-Ministral-70B",
"Envoid/Llama-3.05-Nemotron-Tenyxchat-Storybreaker-70B",
"inflatebot/MN-12B-Mag-Mell-R1",
"Steelskull/L3.3-MS-Evayale-70B",
"NeverSleep/Llama-3-Lumimaid-70B-v0.1",
"Steelskull/L3.3-MS-Evalebis-70b",
"featherless-ai/Qwerky-72B",
"TheDrummer/Anubis-70B-v1",
"TheDrummer/Anubis-70B-v1.1",
"Qwen2.5-32B-EVA-v0.2",
"meta-llama/llama-3.2-3b-instruct",
"Meta-Llama-3-1-8B-Instruct-FP8",
"Sao10K/L3.1-70B-Hanami-x1",
"TheDrummer/Rocinante-12B-v1.1",
"Sao10K/L3.3-70B-Euryale-v2.3",
"Sao10K/L3.1-70B-Euryale-v2.2",
"Steelskull/L3.3-Cu-Mai-R1-70b",
"TheDrummer/UnslopNemo-12B-v4.1",
"MarinaraSpaghetti/NemoMix-Unleashed-12B",
"VongolaChouko/Starcannon-Unleashed-12B-v1.0",
"nothingiisreal/L3.1-70B-Celeste-V0.1-BF16",
"Infermatic/MN-12B-Inferor-v0.0",
"huihui-ai/DeepSeek-R1-Distill-Qwen-32B-abliterated",
"huihui-ai/DeepSeek-R1-Distill-Llama-70B-abliterated",
"deepseek-reasoner-cheaper",
"unsloth/gemma-3-27b-it",
"unsloth/gemma-3-12b-it",
"unsloth/gemma-3-4b-it",
"unsloth/gemma-3-1b-it",
"OpenGVLab/InternVL3-78B",
"Qwen/Qwen3-VL-235B-A22B-Instruct",
"THUDM/GLM-Z1-9B-0414",
"THUDM/GLM-4-9B-0414",
"THUDM/GLM-4-32B-0414",
"Llama-3.3-70B-Mokume-Gane-R1",
"Llama-3.3-70B-MS-Nevoria",
"Llama-3.3-70B-Cirrus-x1",
"Llama-3.3-70B-Bigger-Body",
"Llama-3.3-70B-Forgotten-Safeword-3.6",
"Llama-3.3-70B-Legion-V2.1",
"Mistral-Nemo-12B-Instruct-2407",
"Llama-3.3-70B-Electra-R1",
"Llama-3.3-70B-Vulpecula-R1",
"Llama-3.3-70B-Magnum-v4-SE",
"Llama-3.3-70B-Fallen-R1-v1",
"Llama-3.3-70B-Cu-Mai-R1",
"Llama-3.3-70B-ArliAI-RPMax-v1.4",
"Llama-3.3-70B-Electranova-v1.0",
"Gemma-3-27B-it",
"Llama-3.3+(3.1v3.3)-70B-Hanami-x1",
"Llama-3.3-70B-Mhnnn-x1",
"Llama-3.3-70B-GeneticLemonade-Unleashed-v3",
"Llama-3.3+(3v3.3)-70B-TenyxChat-DaybreakStorywriter",
"Gemma-3-27B-Glitter",
"Llama-3.3-70B-Forgotten-Abomination-v5.0",
"Llama-3.3-70B-Fallen-v1",
"Gemma-3-27B-CardProjector-v4",
"Llama-3.3-70B-StrawberryLemonade-v1.0",
"Llama-3.3+(3.1v3.3)-70B-New-Dawn-v1.1",
"Llama-3.3-70B-Strawberrylemonade-v1.2",
"Llama-3.3-70B-Shakudo",
"Llama-3.3-70B-Predatorial-Extasy",
"Llama-3.3-70B-ArliAI-RPMax-v3",
"Llama-3.3-70B-Argunaut-1-SFT",
"Llama-3.3-70B-Dark-Ages-v0.1",
"Llama-3.3-70B-Aurora-Borealis",
"Llama-3.3-70B-The-Omega-Directive-Unslop-v2.0",
"Llama-3.3-70B-RAWMAW",
"Llama-3.3-70B-Anthrobomination",
"Llama-3.3-70B-The-Omega-Directive-Unslop-v2.1",
"Llama-3.3-70B-Sapphira-0.1",
"GLM-4.5-Air-Derestricted",
"GLM-4.5-Air-Steam-Derestricted",
"GLM-4.5-Air-Iceblink-v2-Derestricted",
"GLM-4.5-Air-Iceblink-Derestricted",
"GLM-4.5-Air-Iceblink-v2",
"Llama-3.3-70B-Incandescent-Malevolence",
"Llama-3.3-70B-Nova",
"Llama-3.3-70B-Ignition-v0.1",
"Llama-3.3-70B-GeneticLemonade-Opus",
"Llama-3.3-70B-Sapphira-0.2",
"nvidia/nvidia-nemotron-nano-9b-v2"
],
"transformer": {
"use": [
"nanogpt"
]
}
}
],
"StatusLine": {
"enabled": true,
"currentStyle": "default",
"default": {
"modules": [
{
"type": "workDir",
"icon": "🧷",
"text": "{{workDirName}} ||",
"color": "bright_blue"
},
{
"type": "gitBranch",
"icon": "🌿",
"text": "{{gitBranch}} ||",
"color": "bright_green"
},
{
"type": "model",
"icon": "🤖",
"text": "{{model}} ||",
"color": "bright_yellow"
},
{
"type": "usage",
"icon": "📊",
"text": "{{inputTokens}} → {{outputTokens}}",
"color": "bright_magenta"
}
]
}
},
"Router": {
"default": "qwen/qwen3-coder",
"background": "Qwen/Qwen3-Next-80B-A3B-Instruct",
"think": "moonshotai/kimi-k2-thinking",
"longContext": "minimax/minimax-01",
"longContextThreshold": 60000,
"webSearch": "z-ai/glm-4.6:online",
"image": "qwen3-vl-235b-a22b-instruct-original"
},
"CUSTOM_ROUTER_PATH": ""
}
# GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 [Free Software Foundation, Inc.](http://fsf.org/)
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
## Preamble
The GNU General Public License is a free, copyleft license for software and
other kinds of works.
The licenses for most software and other practical works are designed to take
away your freedom to share and change the works. By contrast, the GNU General
Public License is intended to guarantee your freedom to share and change all
versions of a program--to make sure it remains free software for all its users.
We, the Free Software Foundation, use the GNU General Public License for most
of our software; it applies also to any other work released this way by its
authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our
General Public Licenses are designed to make sure that you have the freedom to
distribute copies of free software (and charge for them if you wish), that you
receive source code or can get it if you want it, that you can change the
software or use pieces of it in new free programs, and that you know you can do
these things.
To protect your rights, we need to prevent others from denying you these rights
or asking you to surrender the rights. Therefore, you have certain
responsibilities if you distribute copies of the software, or if you modify it:
responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for
a fee, you must pass on to the recipients the same freedoms that you received.
You must make sure that they, too, receive or can get the source code. And you
must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps:
1. assert copyright on the software, and
2. offer you this License giving you legal permission to copy, distribute
and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that
there is no warranty for this free software. For both users' and authors' sake,
the GPL requires that modified versions be marked as changed, so that their
problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified
versions of the software inside them, although the manufacturer can do so. This
is fundamentally incompatible with the aim of protecting users' freedom to
change the software. The systematic pattern of such abuse occurs in the area of
products for individuals to use, which is precisely where it is most
unacceptable. Therefore, we have designed this version of the GPL to prohibit
the practice for those products. If such problems arise substantially in other
domains, we stand ready to extend this provision to those domains in future
versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States
should not allow patents to restrict development and use of software on
general-purpose computers, but in those that do, we wish to avoid the special
danger that patents applied to a free program could make it effectively
proprietary. To prevent this, the GPL assures that patents cannot be used to
render the program non-free.
The precise terms and conditions for copying, distribution and modification
follow.
## TERMS AND CONDITIONS
### 0. Definitions.
*This License* refers to version 3 of the GNU General Public License.
*Copyright* also means copyright-like laws that apply to other kinds of works,
such as semiconductor masks.
*The Program* refers to any copyrightable work licensed under this License.
Each licensee is addressed as *you*. *Licensees* and *recipients* may be
individuals or organizations.
To *modify* a work means to copy from or adapt all or part of the work in a
fashion requiring copyright permission, other than the making of an exact copy.
The resulting work is called a *modified version* of the earlier work or a work
*based on* the earlier work.
A *covered work* means either the unmodified Program or a work based on the
Program.
To *propagate* a work means to do anything with it that, without permission,
would make you directly or secondarily liable for infringement under applicable
copyright law, except executing it on a computer or modifying a private copy.
Propagation includes copying, distribution (with or without modification),
making available to the public, and in some countries other activities as well.
To *convey* a work means any kind of propagation that enables other parties to
make or receive copies. Mere interaction with a user through a computer
network, with no transfer of a copy, is not conveying.
An interactive user interface displays *Appropriate Legal Notices* to the
extent that it includes a convenient and prominently visible feature that
1. displays an appropriate copyright notice, and
2. tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the work
under this License, and how to view a copy of this License.
If the interface presents a list of user commands or options, such as a menu, a
prominent item in the list meets this criterion.
### 1. Source Code.
The *source code* for a work means the preferred form of the work for making
modifications to it. *Object code* means any non-source form of a work.
A *Standard Interface* means an interface that either is an official standard
defined by a recognized standards body, or, in the case of interfaces specified
for a particular programming language, one that is widely used among developers
working in that language.
The *System Libraries* of an executable work include anything, other than the
work as a whole, that (a) is included in the normal form of packaging a Major
Component, but which is not part of that Major Component, and (b) serves only
to enable use of the work with that Major Component, or to implement a Standard
Interface for which an implementation is available to the public in source code
form. A *Major Component*, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (if any) on
which the executable work runs, or a compiler used to produce the work, or an
object code interpreter used to run it.
The *Corresponding Source* for a work in object code form means all the source
code needed to generate, install, and (for an executable work) run the object
code and to modify the work, including scripts to control those activities.
However, it does not include the work's System Libraries, or general-purpose
tools or generally available free programs which are used unmodified in
performing those activities but which are not part of the work. For example,
Corresponding Source includes interface definition files associated with source
files for the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require, such as
by intimate data communication or control flow between those subprograms and
other parts of the work.
The Corresponding Source need not include anything that users can regenerate
automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
### 2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on
the Program, and are irrevocable provided the stated conditions are met. This
License explicitly affirms your unlimited permission to run the unmodified
Program. The output from running a covered work is covered by this License only
if the output, given its content, constitutes a covered work. This License
acknowledges your rights of fair use or other equivalent, as provided by
copyright law.
You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey
covered works to others for the sole purpose of having them make modifications
exclusively for you, or provide you with facilities for running those works,
provided that you comply with the terms of this License in conveying all
material for which you do not control copyright. Those thus making or running
the covered works for you must do so exclusively on your behalf, under your
direction and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes it
unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure
under any applicable law fulfilling obligations under article 11 of the WIPO
copyright treaty adopted on 20 December 1996, or similar laws prohibiting or
restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention is
effected by exercising rights under this License with respect to the covered
work, and you disclaim any intention to limit operation or modification of the
work as a means of enforcing, against the work's users, your or third parties'
legal rights to forbid circumvention of technological measures.
### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it,
in any medium, provided that you conspicuously and appropriately publish on
each copy an appropriate copyright notice; keep intact all notices stating that
this License and any non-permissive terms added in accord with section 7 apply
to the code; keep intact all notices of the absence of any warranty; and give
all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may
offer support or warranty protection for a fee.
### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it
from the Program, in the form of source code under the terms of section 4,
provided that you also meet all of these conditions:
- a) The work must carry prominent notices stating that you modified it, and
giving a relevant date.
- b) The work must carry prominent notices stating that it is released under
this License and any conditions added under section 7. This requirement
modifies the requirement in section 4 to *keep intact all notices*.
- c) You must license the entire work, as a whole, under this License to
anyone who comes into possession of a copy. This License will therefore
apply, along with any applicable section 7 additional terms, to the whole
of the work, and all its parts, regardless of how they are packaged. This
License gives no permission to license the work in any other way, but it
does not invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your work need
not make them do so.
A compilation of a covered work with other separate and independent works,
which are not by their nature extensions of the covered work, and which are not
combined with it such as to form a larger program, in or on a volume of a
storage or distribution medium, is called an *aggregate* if the compilation and
its resulting copyright are not used to limit the access or legal rights of the
compilation's users beyond what the individual works permit. Inclusion of a
covered work in an aggregate does not cause this License to apply to the other
parts of the aggregate.
### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4
and 5, provided that you also convey the machine-readable Corresponding Source
under the terms of this License, in one of these ways:
- a) Convey the object code in, or embodied in, a physical product (including
a physical distribution medium), accompanied by the Corresponding Source
fixed on a durable physical medium customarily used for software
interchange.
- b) Convey the object code in, or embodied in, a physical product (including
a physical distribution medium), accompanied by a written offer, valid for
at least three years and valid for as long as you offer spare parts or
customer support for that product model, to give anyone who possesses the
object code either
1. a copy of the Corresponding Source for all the software in the product
that is covered by this License, on a durable physical medium
customarily used for software interchange, for a price no more than your
reasonable cost of physically performing this conveying of source, or
2. access to copy the Corresponding Source from a network server at no
charge.
- c) Convey individual copies of the object code with a copy of the written
offer to provide the Corresponding Source. This alternative is allowed only
occasionally and noncommercially, and only if you received the object code
with such an offer, in accord with subsection 6b.
- d) Convey the object code by offering access from a designated place
(gratis or for a charge), and offer equivalent access to the Corresponding
Source in the same way through the same place at no further charge. You
need not require recipients to copy the Corresponding Source along with the
object code. If the place to copy the object code is a network server, the
Corresponding Source may be on a different server operated by you or a
third party) that supports equivalent copying facilities, provided you
maintain clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the Corresponding
Source, you remain obligated to ensure that it is available for as long as
needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission, provided you
inform other peers where the object code and Corresponding Source of the
work are being offered to the general public at no charge under subsection
6d.
A separable portion of the object code, whose source code is excluded from the
Corresponding Source as a System Library, need not be included in conveying the
object code work.
A *User Product* is either
1. a *consumer product*, which means any tangible personal property which is
normally used for personal, family, or household purposes, or
2. anything designed or sold for incorporation into a dwelling.
In determining whether a product is a consumer product, doubtful cases shall be
resolved in favor of coverage. For a particular product received by a
particular user, *normally used* refers to a typical or common use of that
class of product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected to use,
the product. A product is a consumer product regardless of whether the product
has substantial commercial, industrial or non-consumer uses, unless such uses
represent the only significant mode of use of the product.
*Installation Information* for a User Product means any methods, procedures,
authorization keys, or other information required to install and execute
modified versions of a covered work in that User Product from a modified
version of its Corresponding Source. The information must suffice to ensure
that the continued functioning of the modified object code is in no case
prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as part of a
transaction in which the right of possession and use of the User Product is
transferred to the recipient in perpetuity or for a fixed term (regardless of
how the transaction is characterized), the Corresponding Source conveyed under
this section must be accompanied by the Installation Information. But this
requirement does not apply if neither you nor any third party retains the
ability to install modified object code on the User Product (for example, the
work has been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates for a
work that has been modified or installed by the recipient, or for the User
Product in which it has been modified or installed. Access to a network may be
denied when the modification itself materially and adversely affects the
operation of the network or violates the rules and protocols for communication
across the network.
Corresponding Source conveyed, and Installation Information provided, in accord
with this section must be in a format that is publicly documented (and with an
implementation available to the public in source code form), and must require
no special password or key for unpacking, reading or copying.
### 7. Additional Terms.
*Additional permissions* are terms that supplement the terms of this License by
making exceptions from one or more of its conditions. Additional permissions
that are applicable to the entire Program shall be treated as though they were
included in this License, to the extent that they are valid under applicable
law. If additional permissions apply only to part of the Program, that part may
be used separately under those permissions, but the entire Program remains
governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional
permissions may be written to require their own removal in certain cases when
you modify the work.) You may place additional permissions on material, added
by you to a covered work, for which you have or can give appropriate copyright
permission.
Notwithstanding any other provision of this License, for material you add to a
covered work, you may (if authorized by the copyright holders of that material)
supplement the terms of this License with terms:
- a) Disclaiming warranty or limiting liability differently from the terms of
sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices displayed
by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in reasonable
ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors or authors
of the material; or
- e) Declining to grant rights under trademark law for use of some trade
names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that material by
anyone who conveys the material (or modified versions of it) with
contractual assumptions of liability to the recipient, for any liability
that these contractual assumptions directly impose on those licensors and
authors.
All other non-permissive additional terms are considered *further restrictions*
within the meaning of section 10. If the Program as you received it, or any
part of it, contains a notice stating that it is governed by this License along
with a term that is a further restriction, you may remove that term. If a
license document contains a further restriction but permits relicensing or
conveying under this License, you may add to a covered work material governed
by the terms of that license document, provided that the further restriction
does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place,
in the relevant source files, a statement of the additional terms that apply to
those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a
separately written license, or stated as exceptions; the above requirements
apply either way.
### 8. Termination.
You may not propagate or modify a covered work except as expressly provided
under this License. Any attempt otherwise to propagate or modify it is void,
and will automatically terminate your rights under this License (including any
patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a
particular copyright holder is reinstated
- a) provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and
- b) permanently, if the copyright holder fails to notify you of the
violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated
permanently if the copyright holder notifies you of the violation by some
reasonable means, this is the first time you have received notice of violation
of this License (for any work) from that copyright holder, and you cure the
violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses
of parties who have received copies or rights from you under this License. If
your rights have been terminated and not permanently reinstated, you do not
qualify to receive new licenses for the same material under section 10.
### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy
of the Program. Ancillary propagation of a covered work occurring solely as a
consequence of using peer-to-peer transmission to receive a copy likewise does
not require acceptance. However, nothing other than this License grants you
permission to propagate or modify any covered work. These actions infringe
copyright if you do not accept this License. Therefore, by modifying or
propagating a covered work, you indicate your acceptance of this License to do
so.
### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a
license from the original licensors, to run, modify and propagate that work,
subject to this License. You are not responsible for enforcing compliance by
third parties with this License.
An *entity transaction* is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered work
results from an entity transaction, each party to that transaction who receives
a copy of the work also receives whatever licenses to the work the party's
predecessor in interest had or could give under the previous paragraph, plus a
right to possession of the Corresponding Source of the work from the
predecessor in interest, if the predecessor has it or can get it with
reasonable efforts.
You may not impose any further restrictions on the exercise of the rights
granted or affirmed under this License. For example, you may not impose a
license fee, royalty, or other charge for exercise of rights granted under this
License, and you may not initiate litigation (including a cross-claim or
counterclaim in a lawsuit) alleging that any patent claim is infringed by
making, using, selling, offering for sale, or importing the Program or any
portion of it.
### 11. Patents.
A *contributor* is a copyright holder who authorizes use under this License of
the Program or a work on which the Program is based. The work thus licensed is
called the contributor's *contributor version*.
A contributor's *essential patent claims* are all patent claims owned or
controlled by the contributor, whether already acquired or hereafter acquired,
that would be infringed by some manner, permitted by this License, of making,
using, or selling its contributor version, but do not include claims that would
be infringed only as a consequence of further modification of the contributor
version. For purposes of this definition, *control* includes the right to grant
patent sublicenses in a manner consistent with the requirements of this
License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent
license under the contributor's essential patent claims, to make, use, sell,
offer for sale, import and otherwise run, modify and propagate the contents of
its contributor version.
In the following three paragraphs, a *patent license* is any express agreement
or commitment, however denominated, not to enforce a patent (such as an express
permission to practice a patent or covenant not to sue for patent
infringement). To *grant* such a patent license to a party means to make such
an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the
Corresponding Source of the work is not available for anyone to copy, free of
charge and under the terms of this License, through a publicly available
network server or other readily accessible means, then you must either
1. cause the Corresponding Source to be so available, or
2. arrange to deprive yourself of the benefit of the patent license for this
particular work, or
3. arrange, in a manner consistent with the requirements of this License, to
extend the patent license to downstream recipients.
*Knowingly relying* means you have actual knowledge that, but for the patent
license, your conveying the covered work in a country, or your recipient's use
of the covered work in a country, would infringe one or more identifiable
patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you
convey, or propagate by procuring conveyance of, a covered work, and grant a
patent license to some of the parties receiving the covered work authorizing
them to use, propagate, modify or convey a specific copy of the covered work,
then the patent license you grant is automatically extended to all recipients
of the covered work and works based on it.
A patent license is *discriminatory* if it does not include within the scope of
its coverage, prohibits the exercise of, or is conditioned on the non-exercise
of one or more of the rights that are specifically granted under this License.
You may not convey a covered work if you are a party to an arrangement with a
third party that is in the business of distributing software, under which you
make payment to the third party based on the extent of your activity of
conveying the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory patent
license
- a) in connection with copies of the covered work conveyed by you (or copies
made from those copies), or
- b) primarily for and in connection with specific products or compilations
that contain the covered work, unless you entered into that arrangement, or
that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available to
you under applicable patent law.
### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not excuse
you from the conditions of this License. If you cannot convey a covered work so
as to satisfy simultaneously your obligations under this License and any other
pertinent obligations, then as a consequence you may not convey it at all. For
example, if you agree to terms that obligate you to collect a royalty for
further conveying from those to whom you convey the Program, the only way you
could satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
### 13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to
link or combine any covered work with a work licensed under version 3 of the
GNU Affero General Public License into a single combined work, and to convey
the resulting work. The terms of this License will continue to apply to the
part which is the covered work, but the special requirements of the GNU Affero
General Public License, section 13, concerning interaction through a network
will apply to the combination as such.
### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU
General Public License from time to time. Such new versions will be similar in
spirit to the present version, but may differ in detail to address new problems
or concerns.
Each version is given a distinguishing version number. If the Program specifies
that a certain numbered version of the GNU General Public License *or any later
version* applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published by
the Free Software Foundation. If the Program does not specify a version number
of the GNU General Public License, you may choose any version ever published by
the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the
GNU General Public License can be used, that proxy's public statement of
acceptance of a version permanently authorizes you to choose that version for
the Program.
Later license versions may give you additional or different permissions.
However, no additional obligations are imposed on any author or copyright
holder as a result of your choosing to follow a later version.
### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
PARTIES PROVIDE THE PROGRAM *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE
PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY
HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot
be given local legal effect according to their terms, reviewing courts shall
apply local law that most closely approximates an absolute waiver of all civil
liability in connection with the Program, unless a warranty or assumption of
liability accompanies a copy of the Program in return for a fee.
## END OF TERMS AND CONDITIONS ###
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible
use to the public, the best way to achieve this is to make it free software
which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach
them to the start of each source file to most effectively state the exclusion
of warranty; and each file should have at least the *copyright* line and a
pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like
this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w` and `show c` should show the appropriate
parts of the General Public License. Of course, your program's commands might
be different; for a GUI interface, you would use an *about box*.
You should also get your employer (if you work as a programmer) or school, if
any, to sign a *copyright disclaimer* for the program, if necessary. For more
information on this, and how to apply and follow the GNU GPL, see
[http://www.gnu.org/licenses/](http://www.gnu.org/licenses/).
The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider
it more useful to permit linking proprietary applications with the library. If
this is what you want to do, use the GNU Lesser General Public License instead
of this License. But first, please read
[http://www.gnu.org/philosophy/why-not-lgpl.html](http://www.gnu.org/philosophy/why-not-lgpl.html).
/**
* NanoGPT API Transformer v0.1.4
*
* This transformer handles requests and responses for NanoGPT API with comprehensive reasoning-to-thinking conversion,
* force reasoning injection, and pseudo-tool syntax cleanup.
*
* ## Purpose:
* 1. Transform requests to always include stream_options: { include_usage: true } parameter (configurable)
* 2. Transform outgoing responses to convert reasoning content to thinking format (Claude Code compatible) (configurable)
* 3. Handle both streaming and non-streaming responses
* 4. Support v1 and v1legacy endpoint formats (uses `reasoning` or `reasoning_content` field in delta)
* 5. Generate fake responses for max_tokens=1 as workaround for models that don't follow OpenAI API standards (configurable)
* 6. Inject reasoning prompts for non-reasoning models to force step-by-step thinking (configurable)
* 7. Clean up pseudo-tool syntax that may leak into reasoning/content from certain providers (configurable)
* 8. Comprehensive error handling for common HTTP status codes (401, 403, 404, 409, 422, 429, 500) with friendly user messages
*
* ## Core Architecture:
*
* ### Main Class: NanoGPTProductionTransformer
* - Extends base transformer functionality with NanoGPT-specific transformations
* - Handles both request transformation and response transformation
* - Supports streaming and non-streaming response processing
* - Provides comprehensive configuration options for all features
*
* ### Key Components:
*
* #### Configuration System:
* - All features are ENABLED by default for backward compatibility and safety
* - Granular control over each transformation feature
* - Parameter omission support (set to -99 to omit from request)
* - Custom parameter injection via `extra` object
*
* #### Reasoning Model Detection:
* - Maintains comprehensive list of known reasoning models (REASONING_MODELS)
* - Intelligent model name matching with fallback logic
* - Automatic exclusion of non-reasoning variants
*
* #### Stream Processing Pipeline:
* - Line-by-line SSE stream processing with state tracking
* - Reasoning content buffering and conversion
* - Pseudo-tool block detection and removal
* - Force reasoning tag parsing with state machine
*
* #### Response Transformation:
* - Non-streaming JSON response processing
* - Streaming response processing with TransformStream
* - Reasoning-to-thinking format conversion
* - Content sanitization and cleanup
*
* ## Configuration Options:
*
* ### Feature Toggles:
*
* - **enableStreamOptions** (default: true)
* WHY: Required for statusline to display token counts (inputTokens/outputTokens) properly.
* RISK if disabled: Token usage statistics won't be available in Claude Code UI statusline.
* SAFE to disable if: You don't need token count visibility OR your API doesn't support stream_options.
*
* - **enableReasoningToThinking** (default: true)
* WHY: Converts NanoGPT's `reasoning`/`reasoning_content` fields to Claude Code's `thinking` format.
* This makes the model's reasoning process visible in Claude Code's "Thinking" mode UI.
* RISK if disabled: Reasoning content will be lost or appear malformed in Claude Code.
* Users won't see the model's step-by-step thinking process.
* SAFE to disable if: Your model doesn't output reasoning content OR you're using a different client.
*
* - **enableFakeResponse** (default: true)
* WHY: Workaround for models that hang or return malformed responses when max_tokens=1.
* Claude Code uses max_tokens=1 when switching models via the /model command.
* RISK if disabled: Model switching via /model command may hang, timeout, or crash the client
* if your NanoGPT model doesn't properly handle max_tokens=1 edge case.
* SAFE to disable if: Your model correctly handles max_tokens=1 requests
* OR you've implemented custom timeout/retry logic
* OR you're not using Claude Code's /model switching feature.
*
* - **enableForceReasoning** (default: false)
* WHY: Forces non-reasoning models to think step-by-step using <reasoning_content> tags.
* Injects a reasoning prompt into the conversation to elicit structured thinking.
* RISK if enabled on reasoning models: Double reasoning, wasted tokens, confused output.
* NOTE: Automatically skipped for models in REASONING_MODELS list.
*
* - **sanitizeToolSyntaxInReasoning** (default: false)
* WHY: Removes pseudo-tool markers (like <|tool_call_begin|>) that may leak into reasoning content.
* Some providers (Kimi, NanoGPT) include these markers in reasoning output.
* RISK if disabled: Pseudo-tool syntax may appear in Claude Code's thinking display.
* SAFE to disable if: Your provider doesn't leak pseudo-tool syntax OR you want to preserve original content.
*
* - **sanitizeToolSyntaxInContent** (default: false)
* WHY: Removes pseudo-tool markers that may leak into regular response content.
* Prevents tool-like syntax from appearing in user-facing responses.
* RISK if disabled: Pseudo-tool syntax may appear in user responses.
* SAFE to disable if: Your provider doesn't leak pseudo-tool syntax into content.
*
* ### Sampling Parameters:
*
* **IMPORTANT: Only 5 parameters are included in API requests by default**
* When no user options are provided, the transformer ONLY sends these 5 parameters to the API:
* - temperature, max_tokens, top_p, frequency_penalty, presence_penalty
* All other parameters are omitted unless explicitly set by the user.
*
* **Range Parameter Support**
* All numeric parameters support range specification using the format "min-max".
* When a range is specified, a random value within that range will be generated for each request.
* This enables dynamic parameter variation while maintaining backward compatibility with exact values.
*
* Range Examples:
* - `"temperature": "0.1-0.8"` - Random temperature between 0.1 and 0.8 for each request
* - `"top_p": "0.7-0.95"` - Random top_p between 0.7 and 0.95 for each request
* - `"frequency_penalty": "-0.5-0.5"` - Random frequency penalty between -0.5 and 0.5
*
* **Default Parameters (included in all requests):**
*
* - **temperature** (default: 0.1, range: 0-2, supports: "0.1-0.8")
* Controls randomness in the output. Higher values make output more random, lower values more deterministic.
* Range example: `"temperature": "0.1-0.8"` generates random values between 0.1 and 0.8.
*
* - **max_tokens** (default: -99, supports: "1000-4000")
* The maximum number of tokens to generate in the response.
* NOTE: Preserved at 1 (model switching) when explicitly requested, omitted when -99 (default, lets Claude Code configure it).
* Range example: `"max_tokens": "1000-4000"` generates random token counts between 1000 and 4000.
*
* - **top_p** (default: 0.95, range: 0-1, supports: "0.7-0.95")
* Controls diversity via nucleus sampling. Lower values make output more focused, higher values more diverse.
* Range example: `"top_p": "0.7-0.95"` generates random values between 0.7 and 0.95.
*
* - **frequency_penalty** (default: 0, range: -2 to 2, supports: "-0.5-0.5")
* Reduces likelihood of repeating the same tokens. Positive values decrease repetition.
* Range example: `"frequency_penalty": "-0.5-0.5"` generates random values between -0.5 and 0.5.
*
* - **presence_penalty** (default: 0, range: -2 to 2, supports: "-0.3-0.3")
* Reduces likelihood of repeating the same topics. Positive values decrease repetition.
* Range example: `"presence_penalty": "-0.3-0.3"` generates random values between -0.3 and 0.3.
*
* **Optional Parameters (only included if explicitly set by user):**
*
* - **parallel_tool_calls** (default: omitted, supports: "true-false" for boolean randomization)
* Whether to enable parallel tool execution in supported models.
* Only included in request if user explicitly sets this parameter.
* Range example: `"parallel_tool_calls": "0-1"` randomly enables/disables parallel tools.
*
* - **top_k** (default: omitted, range: 1-100, supports: "20-80")
* Limits vocabulary to top K tokens. Only included in request if user explicitly sets this parameter.
* Range example: `"top_k": "20-80"` generates random top_k values between 20 and 80.
*
* - **repetition_penalty** (default: omitted, range: 0.1-2.0, supports: "0.8-1.2")
* Alternative repetition control parameter used by some models. Only included if user explicitly sets this parameter.
* Values >1.0 reduce repetition, <1.0 increase it.
* Range example: `"repetition_penalty": "0.8-1.2"` generates random values between 0.8 and 1.2.
*
* ### Optional Parameters (only included if explicitly set by user):
*
* - **reasoning_effort** (default: omitted)
* Controls how much computational effort the model puts into reasoning before generating a response.
* Higher values result in more thorough reasoning but slower responses and higher costs.
* Only applicable to reasoning-capable models. Only included in request if user explicitly sets this parameter.
*
* Valid values:
* - "none": Disables reasoning entirely (fastest)
* - "minimal": Allocates ~10% of max_tokens for reasoning
* - "low": Allocates ~20% of max_tokens for reasoning
* - "medium": Allocates ~50% of max_tokens for reasoning
* - "high": Allocates ~80% of max_tokens for reasoning (slowest but most thorough)
*
* ### Claude Code Integration:
*
* The transformer treats Claude Code's reasoning as a simple on/off switch:
*
* - **When Thinking is ON**: Claude Code sends `{"reasoning": {"effort": "high", "enabled": true}}`
* → Transformer uses the configured `reasoning_effort` from options
* - **When Thinking is OFF**: No reasoning parameter is sent
* → Transformer sets `reasoning_effort` to "none"
*
* **Precedence Order**:
* 1. User's explicit reasoning_effort setting (highest priority)
* 2. Claude Code thinking toggle (ON = configured effort, OFF = "none")
* 3. Transformer configuration default (none)
*
* **Behavior**:
* - CC Thinking acts as an enable/disable switch for reasoning
* - The actual reasoning effort level is controlled by the transformer's `reasoning_effort` option
* - Users can override by explicitly setting `reasoning_effort` in their request
*
* The transformer creates both `reasoning` and `reasoning_effort` parameters for maximum compatibility with NanoGPT.
*
* **IMPORTANT - UltraThink Feature**:
* When a user types "UltraThink" in their prompt, Claude Code will automatically toggle the Thinking mode ON.
* This is a built-in Claude Code feature that triggers extended thinking/reasoning for complex tasks.
* The transformer will then receive the reasoning parameter with `enabled: true` and apply the configured effort level.
*
* ### Optional Parameters (only included if explicitly set by user):
*
* - **cache_control** (default: omitted)
* Enables caching for Claude models. Only applicable to Claude models.
* Only included in request if user explicitly sets this parameter.
* - enabled: Whether to enable caching
* - ttl: Cache time-to-live (e.g., "5m", "1h", "1d")
*
* - **extra** (default: omitted)
* Custom parameters to include in the request. Only included if user explicitly sets this parameter.
* Merged into the request object.
* Example: { "custom_param_1": "value1", "custom_param_2": "value2" }
*
* ## Advanced Features:
*
* ### Parameter Omission:
* Set any numeric parameter to -99 to omit it from the request entirely.
* This is useful when you want to let the model use its default values.
*
* ### Force Reasoning System:
* When enableForceReasoning is true, the transformer:
* 1. Checks if the model is in the REASONING_MODELS list
* 2. If not a reasoning model, injects FORCE_REASONING_PROMPT
* 3. Parses responses for <reasoning_content> tags
* 4. Converts tagged content to thinking format
*
* ### Pseudo-Tool Syntax Cleanup:
* Handles various pseudo-tool markers that may leak from providers:
* - <|tool_calls_section_begin|> / <|tool_calls_section_end|>
* - <|tool_call_begin|> / <|tool_call_end|>
* - <|tool_call_argument_begin|> / <|tool_call_argument_end|>
*
* ## Usage Examples:
*
* ### Basic Usage (All Features Enabled):
* ```javascript
* const transformer = new NanoGPTProductionTransformer({ enable: true });
* ```
*
* ### Custom Configuration:
* ```javascript
* const transformer = new NanoGPTProductionTransformer({
* enable: true,
* enableStreamOptions: true, // Keep token counts
* enableReasoningToThinking: true, // Convert reasoning to thinking
* enableFakeResponse: true, // Handle max_tokens=1 edge case
* enableForceReasoning: false, // Don't force reasoning on non-reasoning models
* sanitizeToolSyntaxInReasoning: true, // Clean up reasoning content
* sanitizeToolSyntaxInContent: false, // Keep content as-is
* temperature: 0.8, // Set temperature
* max_tokens: 2000, // Set max tokens
* top_p: 0.9, // Set top_p
* frequency_penalty: 0.1, // Set frequency penalty
* presence_penalty: 0.1, // Set presence penalty
* parallel_tool_calls: true, // Enable parallel tools
* top_k: 50, // Set top_k
* repetition_penalty: 1.1, // Set repetition penalty
* reasoning_effort: "medium", // Set reasoning effort level
* cache_control: { // Enable cache control
* enabled: true,
* ttl: "10m"
* },
* extra: { // Custom parameters
* custom_param_1: "value1",
* custom_param_2: "value2"
* }
* });
* ```
*
* ### Parameter Omission Example:
* ```javascript
* const transformer = new NanoGPTProductionTransformer({
* enable: true,
* temperature: -99, // Omit temperature from request
* top_p: -99, // Omit top_p from request
* frequency_penalty: -99 // Omit frequency_penalty from request
* });
* ```
*
* ### Range Parameter Example:
* ```javascript
* const transformer = new NanoGPTProductionTransformer({
* enable: true,
* temperature: "0.1-0.8", // Random temperature between 0.1 and 0.8 for each request
* max_tokens: "2000-8192", // Random token count between 2000 and 8192
* top_p: "0.5-0.9", // Random top_p between 0.5 and 0.9
* frequency_penalty: "0-0.3", // Random frequency penalty between 0 and 0.3
* presence_penalty: "0-0.2", // Random presence penalty between 0 and 0.2
* top_k: "20-60", // Random top_k between 20 and 60
* repetition_penalty: "1.0-1.3" // Random repetition penalty between 1.0 and 1.3
* });
* ```
*
* ### Mixed Exact and Range Parameters:
* ```javascript
* const transformer = new NanoGPTProductionTransformer({
* enable: true,
* temperature: "0.2-0.7", // Range: random between 0.2 and 0.7
* max_tokens: 2048, // Exact: always 2048
* top_p: "0.8-0.92", // Range: random between 0.8 and 0.92
* frequency_penalty: 0, // Exact: always 0
* presence_penalty: "-0.1-0.2" // Range: random between -0.1 and 0.2
* });
* ```
*
* ### Reasoning Effort Examples:
* ```javascript
* // High reasoning effort for complex problems
* const transformer = new NanoGPTProductionTransformer({
* enable: true,
* reasoning_effort: "high" // Maximum reasoning (80% of tokens)
* });
*
* // Fast responses for simple tasks
* const transformer = new NanoGPTProductionTransformer({
* enable: true,
* reasoning_effort: "minimal" // Minimal reasoning (10% of tokens)
* });
*
* // Disable reasoning entirely
* const transformer = new NanoGPTProductionTransformer({
* enable: true,
* reasoning_effort: "none" // No reasoning (fastest)
* });
* ```
*
* ## Configuration in config.json:
* ```json
* {
* "transformers": [
* {
* "options": {
* // === Core Feature Toggles ===
* "enable": true,
* "enableStreamOptions": true,
* "enableReasoningToThinking": true,
* "enableFakeResponse": true,
* "enableForceReasoning": false,
* "sanitizeToolSyntaxInReasoning": false,
* "sanitizeToolSyntaxInContent": false,
*
*
* // === Default Sampling Parameters (Only these 5 parameters will be included in API requests) ===
* "temperature": 0.1,
* "max_tokens": -99,
* "top_p": 0.95,
* "frequency_penalty": 0,
* "presence_penalty": 0,
*
* // === Optional Parameters (Only included in API requests when explicitly set by user) ===
* "parallel_tool_calls": true,
* "top_k": 40,
* "repetition_penalty": 1.15,
* "reasoning_effort": "none",
* "cache_control": {
* "enabled": false,
* "ttl": "5m"
* },
* "extra": {
* "custom_param_1": "value1",
* "custom_param_2": "value2"
* }
* },
* "path": "Your\\Path\\To\\The\\Transformer\\File\\nanogpt.js"
* }
* ]
* }
* ```
*
* ## Key Features:
*
* ### Request Transformation:
* - Automatically adds stream_options: { include_usage: true } to all requests (if enabled)
* - Sets sampling parameters (temperature, max_tokens, top_p, etc.)
* - Sets reasoning_effort parameter for NanoGPT models (none, minimal, low, medium, high)
* - Handles Claude Code's reasoning format: {"reasoning": {"effort": "high", "enabled": true}}
* - Injects force reasoning prompt for non-reasoning models (if enabled)
* - Merges custom parameters from `extra` object
* - Preserves original max_tokens=1 (model switching), default -99 leaves max_tokens untouched for Claude Code to configure
*
* ### Response Transformation:
* - Converts NanoGPT `reasoning` deltas to Claude Code `thinking` format (if enabled)
* - Buffers reasoning content and emits as structured thinking blocks
* - Handles both streaming and non-streaming responses
* - Processes force reasoning tags (<reasoning_content>) in responses
* - Sanitizes pseudo-tool syntax from reasoning and content (if enabled)
*
* ### Special Features:
* - Enables statusline to properly count inputTokens and outputTokens via include_usage
* - Enables "Thinking" mode display in Claude Code by converting reasoning to thinking format
* - Generates fake responses when max_tokens=1 to handle models that don't respond correctly to Claude Code's /model command (if enabled)
* - Detects and skips reasoning models for force reasoning to avoid double reasoning
* - Removes pseudo-tool blocks that may leak from certain providers
* - **Comprehensive Error Handling**: Intercepts common HTTP errors (401, 403, 404, 409, 422, 429, 500) and returns user-friendly messages instead of letting errors propagate
*
* ### Error Handling:
* - **401 Unauthorized**: Session required - API key invalid or expired
* - **403 Forbidden**: Insufficient permissions for the requested resource
* - **404 Not Found**: Requested resource does not exist
* - **409 Conflict**: Resource conflict (duplicate creation, wrong state)
* - **422 Invalid Input**: Validation failed for request parameters
* - **429 Rate Limited**: Too many requests - please wait and retry
* - **500 Internal Error**: Server encountered unexpected error
* - Works for both streaming and non-streaming responses
* - Provides clear, actionable error messages to users
*
* ## Supported Models:
*
* ### Built-in Reasoning Models (Force Reasoning Skipped):
* The transformer automatically detects these models and skips force reasoning:
* - DeepSeek: deepseek-reasoner, deepseek-v3.2:thinking, etc.
* - GLM: GLM-4.6:thinking, GLM-4.5-Air:thinking, etc.
* - Qwen: Qwen3-235B-A22B-Thinking-2507, qwq-32b, qvq-max, etc.
* - Hermes: Hermes-4-70B:thinking, etc.
* - Moonshot: kimi-k2-thinking, etc.
* - And many more...
*
* ## Utility Functions:
*
* ### Model Detection:
* - `isReasoningModel(modelName)` - Checks if a model has built-in reasoning capabilities
*
* ### Content Processing:
* - `stripPseudoToolBlocks(text)` - Removes complete pseudo tool sections
* - `stripPseudoToolSyntax(text)` - Removes individual pseudo tool markers
*
* ### Response Generation:
* - `shouldOmitParameter(value)` - Checks if parameter should be omitted (-99)
* - `generateId()` - Generates realistic OpenAI-style IDs
* - `createFakeResponse(model)` - Creates fake responses for max_tokens=1
*
* ### Stream Processing:
* - `processStreamLine()` - Processes individual SSE stream lines with reasoning-to-thinking conversion
* - `processForceReasoningContent()` - Handles force reasoning tag parsing using state machine
* - `handleNonStreamingResponse()` - Processes JSON responses (async function)
* - `handleStreamingResponse()` - Processes streaming responses (async function)
* - `processStream()` - Main stream processing loop (async function, invoked by handleStreamingResponse)
*
* ## Error Handling:
*
* ### Stream Processing:
* - Graceful handling of malformed JSON in SSE streams
* - Buffer size limits (1MB) to prevent memory issues
* - Proper stream cleanup and error propagation
*
* ### Response Processing:
* - Fallback content when pseudo-tool removal empties the response
* - Preservation of original response structure
* - Safe handling of missing or malformed fields
*
* ## Performance Considerations:
*
* ### Memory Usage:
* - Stream buffering with size limits
* - Reasoning content buffering with cleanup
* - Efficient string processing for content sanitization
*
* ### Processing Efficiency:
* - Line-by-line stream processing to minimize latency
* - Conditional feature execution based on configuration
* - Early termination for disabled features
*
* ## Compatibility:
*
* ### API Standards:
* - OpenAI-compatible request/response format
* - Server-Sent Events (SSE) streaming support
* - Standard JSON response handling
*
* ### Claude Code Integration:
* - Thinking mode format compatibility
* - Token count reporting via stream_options
* - Model switching support via max_tokens=1 handling
*
* ## Troubleshooting:
*
* ### Common Issues:
* 1. **Token counts not showing**: Enable enableStreamOptions
* 2. **Reasoning not visible**: Enable enableReasoningToThinking
* 3. **Model switching hangs**: Enable enableFakeResponse
* 4. **Pseudo-tool syntax appears**: Enable sanitizeToolSyntaxInReasoning/Content
* 5. **Double reasoning on reasoning models**: Check REASONING_MODELS list
* 6. **Reasoning effort not working**: Verify reasoning_effort value is one of: "none", "minimal", "low", "medium", "high"
* 7. **Error messages not appearing**: Check that error interception is enabled (built-in, always active)
* 8. **Custom error handling needed**: Modify error messages in the switch statements in transformResponseOut and fetch interceptor
*
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
// ============================================================================
// FORCE REASONING CONFIGURATION
// ============================================================================
/**
* List of reasoning models that already have built-in reasoning capabilities.
* The forceReasoning feature should NOT be applied to these models.
* This list is used to filter out models that don't need prompt injection.
*/
const REASONING_MODELS = [
// DeepSeek Reasoning Models
"deepseek/deepseek-v3.2:thinking",
"deepseek-reasoner",
"deepseek-reasoner-cheaper",
"deepseek-r1",
"deepseek-ai/deepseek-v3.2-exp-thinking",
"deepseek-ai/DeepSeek-V3.1:thinking",
"deepseek-ai/DeepSeek-V3.1-Terminus:thinking",
"deepseek/deepseek-v3.2-speciale",
// Moonshot Reasoning Models
"moonshotai/kimi-k2-thinking",
// GLM Reasoning Models
"GLM-4.5-Air-Iceblink:thinking",
"GLM-4.5-Air-Steam-v1:thinking",
"z-ai/glm-4.6:thinking",
"zai-org/GLM-4.5-Air:thinking",
"THUDM/GLM-Z1-32B-0414",
"THUDM/GLM-Z1-9B-0414",
"zai-org/GLM-4.5:thinking",
// Hermes Reasoning Models
"NousResearch/Hermes-4-70B:thinking",
"nousresearch/hermes-4-405b:thinking",
// Qwen Reasoning Models
"Qwen/Qwen3-235B-A22B-Thinking-2507",
"qwen3-vl-235b-a22b-thinking",
"qwq-32b",
"qwen/qwq-32b-preview",
"qvq-max",
// Other Reasoning Models
"pamanseau/OpenReasoning-Nemotron-32B",
"LLM360/K2-Think",
"tngtech/DeepSeek-TNG-R1T2-Chimera",
"tngtech/DeepSeek-R1T-Chimera",
"Steelskull/L3.3-Nevoria-R1-70b",
"Steelskull/L3.3-Electra-R1-70b",
"Steelskull/L3.3-Damascus-R1",
"inflatebot/MN-12B-Mag-Mell-R1",
"Steelskull/L3.3-Cu-Mai-R1-70b",
"Llama-3.3-70B-Electra-R1",
"Llama-3.3-70B-Vulpecula-R1",
"Llama-3.3-70B-Fallen-R1-v1",
"Llama-3.3-70B-Cu-Mai-R1",
"Llama-3.3-70B-Mokume-Gane-R1",
"huihui-ai/DeepSeek-R1-Distill-Qwen-32B-abliterated",
"huihui-ai/DeepSeek-R1-Distill-Llama-70B-abliterated",
// Newly added models
"Alibaba-NLP/Tongyi-DeepResearch-30B-A3B",
"Envoid/Llama-3.05-Nemotron-Tenyxchat-Storybreaker-70B",
"Ling-Flash-2.0",
"MiniMax-M2",
"Salesforce/Llama-xLAM-2-70b-fc-r",
"deepcogito/cogito-v1-preview-qwen-32B",
"huihui-ai/Llama-3.1-Nemotron-70B-Instruct-HF-abliterated",
"inclusionai/ling-1t",
"meituan-longcat/LongCat-Flash-Chat-FP8",
"microsoft/MAI-DS-R1-FP8",
"minimax/minimax-01",
"nvidia/Llama-3.1-Nemotron-70B-Instruct-HF",
"nvidia/Llama-3.1-Nemotron-Ultra-253B-v1",
"nvidia/Llama-3.3-Nemotron-Super-49B-v1",
"nvidia/Llama-3_3-Nemotron-Super-49B-v1_5",
"nvidia/nvidia-nemotron-nano-9b-v2"
];
/**
* The reasoning prompt that forces non-reasoning models to think step-by-step.
* This prompt is injected into requests when enableForceReasoning is true and
* the model is NOT in the REASONING_MODELS list.
*/
const FORCE_REASONING_PROMPT = `You are an expert reasoning model.
Always think step by step before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
Output format:
<reasoning_content>
Your detailed thinking process goes here
</reasoning_content>
Your final answer must follow after the closing tag above.`;
/**
* Check if a model is a reasoning model that already has built-in reasoning capabilities.
* Uses a three-tier matching strategy:
* 1. Exact match against REASONING_MODELS list (highest priority)
* 2. Check against known non-reasoning variants to avoid false positives
* 3. Fallback pattern matching for unknown models (looks for :thinking, -r1, reasoner, etc.)
* @param {string} modelName - The model name to check (case-insensitive)
* @returns {boolean} True if the model is a reasoning model, false otherwise
* @example
* isReasoningModel("deepseek-reasoner") // true (exact match)
* isReasoningModel("z-ai/glm-4.6:thinking") // true (exact match)
* isReasoningModel("z-ai/glm-4.6") // false (non-reasoning variant)
* isReasoningModel("some-model:thinking") // true (pattern match)
*/
function isReasoningModel(modelName) {
if (!modelName) return false;
const normalizedModel = modelName.toLowerCase();
// First check for exact matches (highest priority)
if (REASONING_MODELS.some(reasoningModel =>
reasoningModel.toLowerCase() === normalizedModel)) {
return true;
}
// Check if the model is explicitly a non-reasoning variant
// This prevents false positives where non-reasoning models match reasoning models
const nonReasoningVariants = [
"z-ai/glm-4.6",
"GLM-4.5-Air-Iceblink",
"GLM-4.5-Air-Steam-v1",
"deepseek/deepseek-v3.2",
"deepseek-ai/DeepSeek-V3.1",
"moonshotai/kimi-k2-instruct",
"NousResearch/Hermes-4-70B",
"nousresearch/hermes-4-405b",
"qwen3-vl-235b-a22b-instruct",
"Qwen/Qwen3-235B-A22B"
];
if (nonReasoningVariants.some(variant =>
variant.toLowerCase() === normalizedModel)) {
return false;
}
// For models not in exact lists, check for reasoning indicators
// Only apply to unknown models to avoid false positives
const hasReasoningIndicators = [
":thinking",
"-thinking",
"-r1",
"reasoner",
"think",
"qwq",
"qvq"
];
return hasReasoningIndicators.some(indicator =>
normalizedModel.includes(indicator));
}
// ============================================================================
// PSEUDO-TOOL SYNTAX CLEANUP UTILITIES
// ============================================================================
/**
* CHAOS TEST CASES FOR PSEUDO-TOOL SYNTAX
*
* Test Case 1 - Intentional pseudo-markers in reasoning:
* Input: "Let me use the tool: <|tool_call_begin|>\n{\"name\": \"bash\", \"arguments\": \"{\\\"command\\\": \\\"ls -la\\\"}\"}\n<|tool_call_end|>\n\nNow I'll execute it."
* Expected: "Let me use the tool: \n\nNow I'll execute it."
*
* Test Case 2 - Accidental marker-like strings in user content:
* Input: "To use Kimi's tools, you write: <|tool_call_begin|> followed by JSON"
* Expected: "To use Kimi's tools, you write: followed by JSON" (sanitized if sanitizeToolSyntaxInContent=true)
*
* Test Case 3 - Broken/malformed markers:
* Input: "Here's my command: <|tool_call_begin\n{\"command\": \"test\"}\n<|tool_call_end|>"
* Expected: "Here's my command: \n{\"command\": \"test\"}\n"
*
* Test Case 4 - Attempted tool injection in reasoning:
* Input: "Reasoning: Let's call tool_search({'query': 'malicious'}) to get data"
* Expected: "Reasoning: Let's call tool_search({'query': 'malicious'}) to get data" (no tool_calls created)
*
* Test Case 5 - Nested markers:
* Input: "Outer: <|tool_call_begin|> Inner: <|tool_call_argument_begin|> data <|tool_call_argument_end|> <|tool_call_end|>"
* Expected: "Outer: Inner: data "
*/
/**
* Remove complete pseudo tool-call sections that span multiple lines.
* Handles the full section markers: <|tool_calls_section_begin|> ... <|tool_calls_section_end|>
* @param {string} text - The text to sanitize
* @returns {string} Text with pseudo tool blocks removed, or original if not a string
*/
function stripPseudoToolBlocks(text) {
if (typeof text !== "string" || !text) return text;
return text.replace(
/<\|tool_calls_section_begin\|>[\s\S]*?<\|tool_calls_section_end\|>/g,
""
);
}
/**
* Strip provider-specific pseudo tool-call markers that sometimes leak into
* reasoning/content (e.g. Kimi <|tool_call_*|> tags).
* This does NOT touch real OpenAI tool_calls fields.
*
* @param {string} text - The text to sanitize
* @returns {string} - The sanitized text
*/
function stripPseudoToolSyntax(text) {
if (typeof text !== "string" || !text) return text;
let cleaned = text;
const originalLength = cleaned.length;
// Remove known Kimi / NanoGPT tool markers
cleaned = cleaned.replace(/<\|tool_calls_section_begin\|>/g, "");
cleaned = cleaned.replace(/<\|tool_calls_section_end\|>/g, "");
cleaned = cleaned.replace(/<\|tool_call_begin\|>/g, "");
cleaned = cleaned.replace(/<\|tool_call_end\|>/g, "");
cleaned = cleaned.replace(/<\|tool_call_argument_begin\|>/g, "");
cleaned = cleaned.replace(/<\|tool_call_argument_end\|>/g, "");
// Optional: normalize excessive whitespace created by removals
cleaned = cleaned.replace(/\s{2,}/g, " ");
return cleaned;
}
// ============================================================================
// RANGE PARAMETER UTILITIES
// ============================================================================
/**
* RANGE PARAMETER SUPPORT - Random Value Generation from Ranges
*
* This section provides utilities for supporting parameter ranges in the format
* "min-max". When a parameter is specified as a range string, the system will
* generate a random value within that range for each request, enabling dynamic
* parameter variation while maintaining backward compatibility with exact values.
*/
/**
* Parses a range string in the format "min-max" and returns range information.
* Supports negative numbers and floating point values.
* @param {string|number} value - The value to parse (can be a range string like "0.1-0.8" or exact number)
* @returns {Object|null} Range object with min, max, and isRange properties, or null if invalid
* @returns {number} return.min - Minimum value (equals max for non-ranges)
* @returns {number} return.max - Maximum value (equals min for non-ranges)
* @returns {boolean} return.isRange - True if input was a range string, false for exact values
* @example
* parseRange(0.5) // { min: 0.5, max: 0.5, isRange: false }
* parseRange("0.2-0.8") // { min: 0.2, max: 0.8, isRange: true }
* parseRange("-0.5-0.5") // { min: -0.5, max: 0.5, isRange: true }
* parseRange("invalid") // null
*/
function parseRange(value) {
// If it's already a number, return as-is with isRange: false
if (typeof value === 'number') {
return {
min: value,
max: value,
isRange: false
};
}
// If it's not a string, return null (invalid)
if (typeof value !== 'string') {
return null;
}
// Trim whitespace
const trimmed = value.trim();
// Check if it matches the range pattern "min-max"
const rangeMatch = trimmed.match(/^(-?\d+\.?\d*)\s*-\s*(-?\d+\.?\d*)$/);
if (!rangeMatch) {
// Not a range, try to parse as single number
const numValue = parseFloat(trimmed);
if (!isNaN(numValue)) {
return {
min: numValue,
max: numValue,
isRange: false
};
}
return null; // Invalid format
}
const min = parseFloat(rangeMatch[1]);
const max = parseFloat(rangeMatch[2]);
// Validate the range
if (isNaN(min) || isNaN(max)) {
return null;
}
// Ensure min <= max
const rangeMin = Math.min(min, max);
const rangeMax = Math.max(min, max);
return {
min: rangeMin,
max: rangeMax,
isRange: true
};
}
/**
* Generates a random number within the specified range using Math.random().
* @param {number} min - Minimum value (inclusive)
* @param {number} max - Maximum value (inclusive)
* @returns {number} Random floating-point number within the range [min, max]
*/
function getRandomInRange(min, max) {
const randomValue = Math.random() * (max - min) + min;
return randomValue;
}
/**
* Resolves a parameter value to a concrete number for the current request.
* If the parameter is a range string, generates a random value within that range.
* If the parameter is an exact number, returns it unchanged.
* @param {string|number} value - The parameter value (range string like "0.1-0.8" or exact number)
* @returns {number|null} Resolved numeric value, or null if input is invalid
* @example
* resolveParameterValue(0.5, 'temperature') // 0.5 (exact value)
* resolveParameterValue("0.2-0.8", 'temperature') // random value between 0.2 and 0.8
*/
function resolveParameterValue(value) {
const parsed = parseRange(value);
if (!parsed) {
return null; // Invalid parameter
}
if (parsed.isRange) {
// Generate random value within range for this request
return getRandomInRange(parsed.min, parsed.max, paramName);
} else {
// Return exact value
return parsed.min; // min == max for non-ranges
}
}
// ============================================================================
// FAKE RESPONSE GENERATION UTILITIES
// ============================================================================
/**
* FAKE RESPONSE GENERATION - Workaround for Model Switch Issues
*
* This section provides a workaround for models that don't respond correctly to
* max_tokens=1 requests. Claude Code uses max_tokens=1 when switching models
* via the `/model` command, but some models don't follow OpenAI API standards
* for this edge case and return malformed responses. Instead of letting these
* problematic responses break the model switching flow, we generate a fake
* response that follows proper OpenAI API format.
*/
/**
* Checks if a parameter value should be omitted (when value equals -99)
* @param {*} value - The parameter value to check
* @returns {boolean} True if the parameter should be omitted, false otherwise
*/
function shouldOmitParameter(value) {
return value === -99;
}
/**
* Generates a realistic OpenAI-style ID for fake responses
* @returns {string} Generated ID in the format chatcmpl-XXXXXXXXXXXXXXaaaa
*/
function generateId() {
let result = 'chatcmpl-';
// 14 random digits
for (let i = 0; i < 14; i++) {
result += Math.floor(Math.random() * 10);
}
// 4 random lowercase letters
const letters = 'abcdefghijklmnopqrstuvwxyz';
for (let i = 0; i < 4; i++) {
result += letters.charAt(Math.floor(Math.random() * letters.length));
}
return result;
}
/**
* Creates a minimal fake response when max_tokens=1
* Used as workaround for models that don't handle max_tokens=1 correctly
* @param {string} model - The model name to include in the response
* @returns {Object} Fake response object following OpenAI API format
*/
function createFakeResponse(model) {
return {
"id": generateId(),
"object": "chat.completion",
"created": Math.floor(Date.now() / 1000),
"model": model,
"choices": [
{
"index": 0,
"finish_reason": "length",
"message": {
"role": "assistant",
"content": "\n"
}
}
]
};
}
// ============================================================================
// STREAM PROCESSING UTILITIES
// ============================================================================
/**
* Processes a single line from the SSE stream with reasoning-to-thinking conversion
* @param {string} line - The line to process
* @param {TransformStreamDefaultController} controller - Stream controller
* @param {TextEncoder} encoder - Text encoder
* @param {Object} context - Stream state context for reasoning tracking
* @param {boolean} context.hasTextContent - Whether non-reasoning content has started
* @param {string} context.reasoningBuffer - Buffer for accumulated reasoning content
* @param {boolean} context.isReasoningFinished - Whether reasoning phase has completed
* @param {boolean} context.enableReasoningToThinking - Whether to convert reasoning to thinking format
* @param {boolean} context.sanitizeToolSyntaxInReasoning - Whether to sanitize pseudo-tool syntax in reasoning
* @param {boolean} context.sanitizeToolSyntaxInContent - Whether to sanitize pseudo-tool syntax in content
* @param {boolean} context.insidePseudoToolBlock - Whether currently inside a pseudo-tool block
* @param {boolean} context.forceReasoningApplied - Whether force reasoning prompt was injected
* @param {string} context.forceReasoningState - State machine state: "SEARCHING", "REASONING", or "FINAL"
* @param {string} context.forceReasoningBuffer - Buffer for force reasoning content
* @param {string} context.forceReasoningPartialMatch - Partial tag match buffer
* @param {string} context.forceReasoningAccumulatedWhitespace - Accumulated whitespace after reasoning
*/
function processStreamLine(line, controller, encoder, context) {
// Skip empty lines
if (!line.trim()) {
return;
}
// Handle [DONE] marker - streaming footer
if (line.trim() === "data: [DONE]") {
controller.enqueue(encoder.encode(line + '\n'));
return;
}
// Process SSE data lines with reasoning-to-thinking transformation
if (line.startsWith("data: ")) {
try {
const jsonData = JSON.parse(line.slice(6));
// Handle pseudo-tool block detection and content dropping
const choice = jsonData.choices?.[0];
const delta = choice?.delta || {};
const rawContent = delta.content;
// 1. Detect tool section markers on the raw content
if (typeof rawContent === "string") {
if (rawContent.includes("<|tool_calls_section_begin|>")) {
context.insidePseudoToolBlock = true;
}
if (rawContent.includes("<|tool_calls_section_end|>")) {
context.insidePseudoToolBlock = false;
}
// 2. Now sanitize, but only if we will forward it
if (context.sanitizeToolSyntaxInContent) {
delta.content = stripPseudoToolSyntax(rawContent);
} else {
delta.content = rawContent;
}
// 3. If we are inside the pseudo tool block, DROP the content entirely
if (context.insidePseudoToolBlock) {
// Do not let this contribute to user-visible content
delete delta.content;
} else {
// Outside pseudo tool block, normal behavior
// Track if normal content has started
if (delta.content && !context.hasTextContent) {
context.hasTextContent = true;
}
// 4. Add fallback if we have reasoning but no content yet
if (!delta.content && !context.hasTextContent && context.reasoningBuffer &&
rawContent && rawContent.includes("<|tool_calls_section_end|>")) {
delta.content = "[Internal tool call removed; see Thinking for details.]";
context.hasTextContent = true;
}
jsonData.choices[0].delta = delta;
}
}
// --- Reasoning / Thinking Logic ---
// NanoGPT v1 endpoint returns `reasoning` or `reasoning_content` field. Transform to `thinking` object (if enabled).
const rawReasoning = jsonData.choices?.[0]?.delta?.reasoning || jsonData.choices?.[0]?.delta?.reasoning_content;
if (rawReasoning && context.enableReasoningToThinking) {
const sanitizedReasoning = context.sanitizeToolSyntaxInReasoning
? stripPseudoToolSyntax(rawReasoning)
: rawReasoning;
context.reasoningBuffer += sanitizedReasoning;
// Create a modified data packet containing 'thinking'
const modifiedData = {
...jsonData,
choices: [{
...jsonData.choices?.[0],
delta: {
...jsonData.choices[0].delta,
thinking: { content: sanitizedReasoning }
}
}]
};
// Clean up the original reasoning fields
if (modifiedData.choices?.[0]?.delta) {
delete modifiedData.choices[0].delta.reasoning;
delete modifiedData.choices[0].delta.reasoning_content;
}
const output = `data: ${JSON.stringify(modifiedData)}\n\n`;
controller.enqueue(encoder.encode(output));
return;
}
// Check if reasoning just finished (content appeared, reasoning buffered, but not marked complete)
if (context.enableReasoningToThinking && jsonData.choices?.[0]?.delta?.content && context.reasoningBuffer && !context.isReasoningFinished) {
context.isReasoningFinished = true;
const signature = Date.now().toString();
// Send a special packet summarizing the full thinking content
const thinkingSummary = {
...jsonData,
choices: [{
...jsonData.choices?.[0],
delta: {
...jsonData.choices[0].delta,
content: null, // Clear content for this specific thinking packet
thinking: {
content: context.reasoningBuffer,
signature: signature
}
}
}]
};
if (thinkingSummary.choices?.[0]?.delta) {
delete thinkingSummary.choices[0].delta.reasoning;
delete thinkingSummary.choices[0].delta.reasoning_content;
}
const thinkingOutput = `data: ${JSON.stringify(thinkingSummary)}\n\n`;
controller.enqueue(encoder.encode(thinkingOutput));
}
// Cleanup reasoning fields if they exist loosely (only if conversion is enabled)
if (context.enableReasoningToThinking) {
if (jsonData.choices?.[0]?.delta?.reasoning) {
delete jsonData.choices[0].delta.reasoning;
}
if (jsonData.choices?.[0]?.delta?.reasoning_content) {
delete jsonData.choices[0].delta.reasoning_content;
}
}
// --- Force Reasoning Tag Parsing (for <reasoning_content> tags in content) ---
// This handles responses from models that were injected with FORCE_REASONING_PROMPT
if (context.forceReasoningApplied && context.enableReasoningToThinking) {
const contentToProcess = jsonData.choices?.[0]?.delta?.content;
if (typeof contentToProcess === "string") {
// Process force reasoning tags using state machine
const result = processForceReasoningContent(contentToProcess, jsonData, context, encoder);
if (result.chunks.length > 0) {
// Emit all generated chunks
for (const chunk of result.chunks) {
controller.enqueue(encoder.encode(chunk));
}
return; // Don't forward the original, we've handled it
}
// If we're currently in REASONING state or SEARCHING, don't forward content yet
if (context.forceReasoningState === "REASONING" ||
(context.forceReasoningState === "SEARCHING" && context.forceReasoningPartialMatch)) {
return;
}
}
}
// Forward the processed chunk
const output = `data: ${JSON.stringify(jsonData)}\n\n`;
controller.enqueue(encoder.encode(output));
} catch (error) {
// If parsing fails, still pass through the original line
controller.enqueue(encoder.encode(line + '\n'));
}
} else {
// Pass through non-data lines (event: lines, etc.) unchanged
controller.enqueue(encoder.encode(line + '\n'));
}
}
/**
* Processes force reasoning content with <reasoning_content> tags using a state machine.
* This parses content that contains reasoning wrapped in special tags and converts it to thinking format.
*
* @param {string} content - The content to process
* @param {Object} chunk - The original SSE chunk data (OpenAI streaming format)
* @param {Object} context - The stream context with state tracking (modified in-place)
* @param {TextEncoder} encoder - Text encoder (unused, kept for API consistency)
* @returns {{chunks: string[]}} Object containing array of SSE-formatted chunk strings to emit
*/
function processForceReasoningContent(content, chunk, context, encoder) {
const chunks = [];
let workingContent = context.forceReasoningPartialMatch + content;
context.forceReasoningPartialMatch = "";
while (workingContent.length > 0) {
if (context.forceReasoningState === "SEARCHING") {
// Look for reasoning start tag
const startIndex = workingContent.indexOf(FORCE_REASONING_START_TAG);
if (startIndex !== -1) {
// Found start tag, switch to REASONING state
workingContent = workingContent.substring(startIndex + FORCE_REASONING_START_TAG.length);
context.forceReasoningState = "REASONING";
} else {
// Check for partial match at the end (tag might be split across chunks)
for (let i = FORCE_REASONING_START_TAG.length - 1; i > 0; i--) {
if (workingContent.endsWith(FORCE_REASONING_START_TAG.substring(0, i))) {
context.forceReasoningPartialMatch = workingContent.substring(workingContent.length - i);
break;
}
}
workingContent = "";
}
} else if (context.forceReasoningState === "REASONING") {
// Look for reasoning end tag
const endIndex = workingContent.indexOf(FORCE_REASONING_END_TAG);
if (endIndex !== -1) {
// Found end tag, extract reasoning content
const reasoningContent = workingContent.substring(0, endIndex);
if (reasoningContent.length > 0) {
context.forceReasoningBuffer += reasoningContent;
// Create thinking delta with reasoning content
const thinkingDelta = {
...chunk.choices[0].delta,
thinking: { content: reasoningContent }
};
delete thinkingDelta.content;
const thinkingChunk = {
...chunk,
choices: [{ ...chunk.choices[0], delta: thinkingDelta }]
};
chunks.push(`data: ${JSON.stringify(thinkingChunk)}\n\n`);
}
// Add signature to mark end of reasoning
const signatureDelta = {
...chunk.choices[0].delta,
thinking: { signature: Date.now().toString() }
};
delete signatureDelta.content;
const signatureChunk = {
...chunk,
choices: [{ ...chunk.choices[0], delta: signatureDelta }]
};
chunks.push(`data: ${JSON.stringify(signatureChunk)}\n\n`);
workingContent = workingContent.substring(endIndex + FORCE_REASONING_END_TAG.length);
context.forceReasoningState = "FINAL";
} else {
// Check for partial end tag match
let contentToProcess = workingContent;
for (let i = FORCE_REASONING_END_TAG.length - 1; i > 0; i--) {
if (workingContent.endsWith(FORCE_REASONING_END_TAG.substring(0, i))) {
context.forceReasoningPartialMatch = workingContent.substring(workingContent.length - i);
contentToProcess = workingContent.substring(0, workingContent.length - i);
break;
}
}
if (contentToProcess.length > 0) {
context.forceReasoningBuffer += contentToProcess;
// Create thinking delta
const thinkingDelta = {
...chunk.choices[0].delta,
thinking: { content: contentToProcess }
};
delete thinkingDelta.content;
const thinkingChunk = {
...chunk,
choices: [{ ...chunk.choices[0], delta: thinkingDelta }]
};
chunks.push(`data: ${JSON.stringify(thinkingChunk)}\n\n`);
}
workingContent = "";
}
} else if (context.forceReasoningState === "FINAL") {
// Handle final content after reasoning (the actual answer)
if (workingContent.length > 0) {
if (/^\s*$/.test(workingContent)) {
// Accumulate whitespace
context.forceReasoningAccumulatedWhitespace += workingContent;
} else {
// Non-whitespace content, emit with accumulated whitespace
const finalContent = context.forceReasoningAccumulatedWhitespace + workingContent;
const finalDelta = {
...chunk.choices[0].delta,
content: finalContent
};
// Remove thinking if present
if (finalDelta.thinking) {
delete finalDelta.thinking;
}
const finalChunk = {
...chunk,
choices: [{ ...chunk.choices[0], delta: finalDelta }]
};
chunks.push(`data: ${JSON.stringify(finalChunk)}\n\n`);
context.forceReasoningAccumulatedWhitespace = "";
}
}
workingContent = "";
}
}
return { chunks };
}
// ============================================================================
// RESPONSE HANDLING UTILITIES
// ============================================================================
/**
* Constants for force reasoning tag parsing
*/
const FORCE_REASONING_START_TAG = "<reasoning_content>";
const FORCE_REASONING_END_TAG = "</reasoning_content>";
/**
* Handles non-streaming JSON responses with reasoning-to-thinking transformation
* @async
* @param {Response} response - The Fetch API Response object containing JSON body
* @param {boolean} [enableReasoningToThinking=true] - Whether to convert reasoning to thinking format
* @param {boolean} [sanitizeToolSyntaxInReasoning=false] - Whether to sanitize pseudo-tool syntax in reasoning
* @param {boolean} [sanitizeToolSyntaxInContent=false] - Whether to sanitize pseudo-tool syntax in content
* @param {boolean} [forceReasoningApplied=false] - Whether force reasoning prompt was injected
* @returns {Promise<Response>} New Response object with transformed JSON body
*/
async function handleNonStreamingResponse(response, enableReasoningToThinking = true, sanitizeToolSyntaxInReasoning = false, sanitizeToolSyntaxInContent = false, forceReasoningApplied = false) {
const data = await response.json();
// Transform reasoning to thinking format for non-streaming responses (if enabled)
// NanoGPT non-streaming may have reasoning or reasoning_content in message object
if (enableReasoningToThinking && data.choices && Array.isArray(data.choices)) {
for (const choice of data.choices) {
if (!choice.message) continue;
// 1) sanitize content if needed
if (sanitizeToolSyntaxInContent && typeof choice.message.content === "string") {
let cleaned = choice.message.content;
const originalLength = cleaned.length;
cleaned = stripPseudoToolBlocks(cleaned);
cleaned = stripPseudoToolSyntax(cleaned);
// Add fallback if content became empty after removing pseudo-tools
if (cleaned.trim() === "" && originalLength > 0) {
cleaned = "[Internal tool call removed; see Thinking for details.]";
}
choice.message.content = cleaned;
}
// 2) reasoning -> thinking with sanitation (from reasoning/reasoning_content fields)
const rawReasoning = choice.message.reasoning || choice.message.reasoning_content;
if (rawReasoning) {
const sanitizedReasoning = sanitizeToolSyntaxInReasoning
? stripPseudoToolSyntax(rawReasoning)
: rawReasoning;
choice.message.thinking = {
content: sanitizedReasoning,
signature: Date.now().toString()
};
delete choice.message.reasoning;
delete choice.message.reasoning_content;
}
// 3) Parse <reasoning_content> tags from content (for forceReasoning responses)
if (forceReasoningApplied && typeof choice.message.content === "string" && !choice.message.thinking) {
const reasoningRegex = /<reasoning_content>([\s\S]*?)<\/reasoning_content>/;
const reasoningMatch = choice.message.content.match(reasoningRegex);
if (reasoningMatch && reasoningMatch[1]) {
const reasoningContent = reasoningMatch[1].trim();
const sanitizedReasoning = sanitizeToolSyntaxInReasoning
? stripPseudoToolSyntax(reasoningContent)
: reasoningContent;
choice.message.thinking = {
content: sanitizedReasoning,
signature: Date.now().toString()
};
// Remove the reasoning tags from content, keeping only the final answer
choice.message.content = choice.message.content
.replace(/<reasoning_content>[\s\S]*?<\/reasoning_content>/, "")
.trim();
}
}
}
}
// Return the transformed data
return new Response(JSON.stringify(data), {
status: response.status,
statusText: response.statusText,
headers: response.headers
});
}
/**
* Handles streaming responses with reasoning-to-thinking transformation
* @async
* @param {Response} response - The Fetch API Response object containing SSE stream body
* @param {boolean} [enableReasoningToThinking=true] - Whether to convert reasoning to thinking format
* @param {boolean} [sanitizeToolSyntaxInReasoning=false] - Whether to sanitize pseudo-tool syntax in reasoning
* @param {boolean} [sanitizeToolSyntaxInContent=false] - Whether to sanitize pseudo-tool syntax in content
* @param {boolean} [forceReasoningApplied=false] - Whether force reasoning prompt was injected
* @returns {Promise<Response>} New Response object with transformed SSE stream body
*/
async function handleStreamingResponse(response, enableReasoningToThinking = true, sanitizeToolSyntaxInReasoning = false, sanitizeToolSyntaxInContent = false, forceReasoningApplied = false) {
if (!response.body) return response;
const decoder = new TextDecoder();
const encoder = new TextEncoder();
// Stream State Tracking for reasoning-to-thinking conversion
const streamContext = {
hasTextContent: false,
reasoningBuffer: "",
isReasoningFinished: false,
enableReasoningToThinking: enableReasoningToThinking,
sanitizeToolSyntaxInReasoning: sanitizeToolSyntaxInReasoning,
sanitizeToolSyntaxInContent: sanitizeToolSyntaxInContent,
insidePseudoToolBlock: false,
// Force reasoning state tracking
forceReasoningApplied: forceReasoningApplied,
forceReasoningState: "SEARCHING", // SEARCHING, REASONING, FINAL
forceReasoningBuffer: "",
forceReasoningPartialMatch: "",
forceReasoningAccumulatedWhitespace: ""
};
// Create a new readable stream for processing with transformation
const transformedStream = new ReadableStream({
start: (controller) => processStream(response.body, controller, decoder, encoder, streamContext)
});
// Return the transformed response with proper headers
return new Response(transformedStream, {
status: response.status,
statusText: response.statusText,
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive"
}
});
}
/**
* Processes the streaming response with reasoning-to-thinking transformation
* @async
* @param {ReadableStream<Uint8Array>} body - The response body stream from Fetch API
* @param {ReadableStreamDefaultController} controller - ReadableStream controller for output
* @param {TextDecoder} decoder - TextDecoder for converting Uint8Array to string
* @param {TextEncoder} encoder - TextEncoder for converting string to Uint8Array
* @param {Object} context - Stream state context for reasoning tracking (see processStreamLine for properties)
* @returns {Promise<void>} Resolves when stream processing is complete
*/
async function processStream(body, controller, decoder, encoder, context) {
const reader = body.getReader();
try {
let buffer = "";
// Read and process the stream
while (true) {
const { done, value } = await reader.read();
if (done) {
// Process any remaining buffer
if (buffer.trim()) {
const lines = buffer.split('\n');
for (const line of lines) {
if (line.trim()) {
processStreamLine(line, controller, encoder, context);
}
}
}
break;
}
// Decode the chunk and add to buffer
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
// Safety buffer limit (1MB)
if (buffer.length > 1e6) {
const lines = buffer.split('\n');
buffer = lines.pop() || ""; // Keep the last partial line
for (const line of lines) {
if (line.trim()) {
processStreamLine(line, controller, encoder, context);
}
}
continue;
}
// Process complete lines
const lines = buffer.split('\n');
buffer = lines.pop() || "";
for (const line of lines) {
if (line.trim()) {
processStreamLine(line, controller, encoder, context);
}
}
}
} catch (error) {
controller.error(error);
} finally {
try {
reader.releaseLock();
} catch (error) {
// Ignore lock release errors
}
controller.close();
}
}
// ============================================================================
// NANO GPT PRODUCTION TRANSFORMER CLASS
// ============================================================================
class NanoGPTProductionTransformer {
/**
* Creates a new NanoGPTProductionTransformer instance
* @param {Object} options - Configuration options for the transformer
* @param {boolean} [options.enable=true] - Whether the transformer is enabled
* @param {boolean} [options.enableStreamOptions=true] - Add stream_options: { include_usage: true } to requests.
* WHY: Required for statusline to show token counts properly.
* RISK if disabled: Token usage stats won't be available in Claude Code UI.
* @param {boolean} [options.enableReasoningToThinking=true] - Convert NanoGPT reasoning format to Claude Code thinking format.
* WHY: Makes reasoning/thinking visible in Claude Code's "Thinking" mode.
* RISK if disabled: Reasoning content will be lost or malformed in Claude Code.
* @param {boolean} [options.enableFakeResponse=true] - Generate fake response when max_tokens=1.
* WHY: Workaround for models that don't handle max_tokens=1 correctly (Claude Code uses this for /model switching).
* RISK if disabled: Model switching via /model command may hang or fail if the model doesn't respond properly.
* SAFE to disable if: Your model correctly handles max_tokens=1 OR you implement timeout/retry logic.
* @param {boolean} [options.enableForceReasoning=false] - Inject reasoning prompt for non-reasoning models.
* WHY: Forces models without built-in reasoning to think step-by-step using <reasoning_content> tags.
* RISK if enabled on reasoning models: Double reasoning, wasted tokens, confused output.
* NOTE: Automatically skipped for models in REASONING_MODELS list.
* @param {number|string} [options.temperature=0.1] - Controls randomness in output (0-2). Supports range strings like "0.1-0.8".
* @param {number|string} [options.max_tokens=-99] - Maximum tokens to generate. Supports range strings. Preserved at 1 (model switching), default -99 leaves untouched for Claude Code to configure.
* @param {number|string} [options.top_p=0.95] - Nucleus sampling parameter (0-1). Supports range strings.
* @param {number|string} [options.frequency_penalty=0] - Reduces token repetition (-2 to 2). Supports range strings.
* @param {number|string} [options.presence_penalty=0] - Reduces topic repetition (-2 to 2). Supports range strings.
* @param {boolean|number|string} [options.parallel_tool_calls=true] - Whether to enable parallel tool execution. Supports range for randomization.
* @param {number|string|null} [options.top_k=40] - Limits vocabulary to top K tokens (1-100). Set to null to omit. Supports range strings.
* @param {number|string} [options.repetition_penalty=1.15] - Alternative repetition control (0.1-2.0). Supports range strings.
* @param {Object} [options.cache_control] - Cache control settings (default: omitted)
* @param {boolean} options.cache_control.enabled - Whether to enable caching
* @param {string} options.cache_control.ttl - Cache TTL (e.g., "5m", "1h")
* @param {boolean} [options.sanitizeToolSyntaxInReasoning=false] - Whether to sanitize pseudo-tool syntax in reasoning content
* @param {boolean} [options.sanitizeToolSyntaxInContent=false] - Whether to sanitize pseudo-tool syntax in regular content
* @param {string} [options.reasoning_effort="low"] - Reasoning effort level for NanoGPT models.
* Valid values: "none", "minimal", "low", "medium", "high".
* Controls computational effort for reasoning (none=fastest, high=slowest but most thorough).
* **Note**: Can be overridden by Claude Code's thinking mode:
* - thinking.enabled → "medium" (if not explicitly set by user)
* - thinking.disabled → "none" (if not explicitly set by user)
* User's explicit reasoning_effort always takes precedence.
* @param {Object} [options.extra={}] - Custom parameters to merge into the request
*
* @description **Parameter Omission Feature**: Set any numeric parameter to -99 to omit it from the request.
* @description **Range Parameter Support**: Numeric parameters accept range strings like "0.1-0.8" to generate random values per request.
* @description **Custom Parameters**: Add custom parameters via the 'extra' object, which will be merged into the request.
* @description **Reasoning Effort Levels**: none (no reasoning), minimal (~10% tokens), low (~20% tokens), medium (~50% tokens), high (~80% tokens).
*/
constructor(options) {
this.name = "nanogpt";
this.options = options;
this.enable = this.options?.enable ?? true;
// Feature toggles with safe defaults (all enabled)
this.enableStreamOptions = this.options?.enableStreamOptions ?? true;
this.enableReasoningToThinking = this.options?.enableReasoningToThinking ?? true;
this.enableFakeResponse = this.options?.enableFakeResponse ?? true;
this.enableForceReasoning = this.options?.enableForceReasoning ?? false;
// Sampling parameters (support both exact numbers and range strings)
// Default parameter values for optimal performance
this.temperature = this.options?.temperature ?? 0.1;
this.max_tokens = this.options?.max_tokens ?? -99;
this.top_p = this.options?.top_p ?? 0.95;
this.frequency_penalty = this.options?.frequency_penalty ?? 0;
this.presence_penalty = this.options?.presence_penalty ?? 0;
this.parallel_tool_calls = this.options?.parallel_tool_calls ?? true;
this.top_k = this.options?.top_k ?? 40; // Balances exploration and exploitation for code tokens 8
this.repetition_penalty = this.options?.repetition_penalty ?? 1.15; // Optimal for preventing structural repetition in code 35
this.cache_control = this.options?.cache_control ?? null;
// Reasoning effort parameter for NanoGPT models
this.reasoning_effort = this.options?.reasoning_effort ?? "none";
// Store range configurations for parameters that support ranges
this._rangeConfigs = {
temperature: parseRange(this.temperature),
max_tokens: parseRange(this.max_tokens),
top_p: parseRange(this.top_p),
frequency_penalty: parseRange(this.frequency_penalty),
presence_penalty: parseRange(this.presence_penalty),
parallel_tool_calls: parseRange(this.parallel_tool_calls),
top_k: parseRange(this.top_k),
repetition_penalty: parseRange(this.repetition_penalty)
};
// pseudo-tool cleanup flags
this.sanitizeToolSyntaxInReasoning = this.options?.sanitizeToolSyntaxInReasoning ?? false;
this.sanitizeToolSyntaxInContent = this.options?.sanitizeToolSyntaxInContent ?? false;
// Custom parameters support
this.extra = this.options?.extra ?? {};
this.lastRequest = null;
}
/**
* Transforms incoming requests to include stream_options parameter and sampling parameters
* @async
* @param {Object} request - The incoming request object (OpenAI-compatible format)
* @param {string} [request.model] - The model name for reasoning model detection
* @param {number} [request.max_tokens] - Original max_tokens (preserved if 1 for model switching, omitted if -99, left unchanged if -1 for Claude Code)
* @param {Array} [request.messages] - Messages array for force reasoning injection
* @returns {Promise<Object>} The modified request object with stream_options and parameters applied
*/
async transformRequestIn(request) {
if (!this.enable) {
return request;
}
// Store the request for later inspection in transformResponseOut
this.lastRequest = { ...request };
// Create a copy of the request to avoid mutating the original
const modifiedRequest = { ...request };
// Conditionally include stream_options: { include_usage: true }
// Only add if enableStreamOptions is true (default)
if (this.enableStreamOptions) {
modifiedRequest.stream_options = {
include_usage: true,
...modifiedRequest.stream_options
};
}
// Set sampling parameters (resolve ranges to actual values for each request)
// ONLY include the 5 specified parameters when no user options provided
if (!shouldOmitParameter(this.temperature)) {
const resolvedTemp = resolveParameterValue(this.temperature, 'temperature');
if (resolvedTemp !== null) {
modifiedRequest.temperature = resolvedTemp;
}
}
// Handle max_tokens with three distinct cases:
// Case 1: max_tokens=1 - preserve for fake response generation (model switching)
// Case 2: this.max_tokens=-99 (config default) - don't touch, leave CC's value unchanged
// Case 3: Use configured value for other cases (user explicitly set max_tokens in config)
const shouldPreserveMaxTokens = request.max_tokens === 1;
const configOmitsMaxTokens = shouldOmitParameter(this.max_tokens); // -99 means leave CC's value unchanged (default)
if (shouldPreserveMaxTokens) {
// Case 1: Preserve max_tokens=1 for fake response
modifiedRequest.max_tokens = request.max_tokens;
} else if (configOmitsMaxTokens) {
// Case 2: Config says -99 (default), don't touch max_tokens - leave CC's original value
// Do nothing, let request.max_tokens pass through unchanged
} else {
// Case 3: Use configured value (user explicitly set max_tokens in config)
const resolvedMaxTokens = resolveParameterValue(this.max_tokens, 'max_tokens');
if (resolvedMaxTokens !== null) {
modifiedRequest.max_tokens = Math.round(resolvedMaxTokens); // max_tokens should be integer
}
}
if (!shouldOmitParameter(this.top_p)) {
const resolvedTopP = resolveParameterValue(this.top_p, 'top_p');
if (resolvedTopP !== null) {
modifiedRequest.top_p = resolvedTopP;
}
}
if (!shouldOmitParameter(this.frequency_penalty)) {
const resolvedFreqPenalty = resolveParameterValue(this.frequency_penalty, 'frequency_penalty');
if (resolvedFreqPenalty !== null) {
modifiedRequest.frequency_penalty = resolvedFreqPenalty;
}
}
if (!shouldOmitParameter(this.presence_penalty)) {
const resolvedPresencePenalty = resolveParameterValue(this.presence_penalty, 'presence_penalty');
if (resolvedPresencePenalty !== null) {
modifiedRequest.presence_penalty = resolvedPresencePenalty;
}
}
// ONLY include other parameters if explicitly set by user in options
// Check if user explicitly provided these parameters in the original request
if (request.parallel_tool_calls !== undefined) {
const resolvedParallelTools = resolveParameterValue(this.parallel_tool_calls, 'parallel_tool_calls');
if (resolvedParallelTools !== null) {
modifiedRequest.parallel_tool_calls = Boolean(resolvedParallelTools); // Ensure boolean
}
}
// Only add top_k if user explicitly set it and it's not null and not -99
if (request.top_k !== undefined && this.top_k !== null && !shouldOmitParameter(this.top_k)) {
const resolvedTopK = resolveParameterValue(this.top_k, 'top_k');
if (resolvedTopK !== null) {
modifiedRequest.top_k = Math.round(resolvedTopK); // top_k should be integer
}
}
if (request.repetition_penalty !== undefined) {
const resolvedRepetitionPenalty = resolveParameterValue(this.repetition_penalty, 'repetition_penalty');
if (resolvedRepetitionPenalty !== null) {
modifiedRequest.repetition_penalty = resolvedRepetitionPenalty;
}
}
// Set cache control only if user explicitly enabled it
if (request.cache_control !== undefined && this.cache_control && this.cache_control.enabled) {
modifiedRequest.cache_control = this.cache_control;
}
// ============================================================================
// CLAUDE CODE REASONING FORMAT INTEGRATION
// ============================================================================
// Handle Claude Code's reasoning format as a simple on/off switch
// When CC Thinking is ON: set reasoning.enabled=true, exclude=false with configured effort
// When CC Thinking is OFF: set reasoning.enabled=false, exclude=true, effort="none"
// This applies to BOTH reasoning and non-reasoning models consistently
//
// Precedence: user's explicit reasoning_effort > CC thinking toggle > config default
let finalReasoningEffort = this.reasoning_effort; // Start with config default (e.g., "high")
let reasoningSource = "configuration";
let ccThinkingEnabled = false; // Track CC Thinking state for Force Reasoning logic
// Check if user explicitly set reasoning_effort in the original request (highest precedence)
const userSetReasoningEffort = 'reasoning_effort' in request;
if (userSetReasoningEffort) {
// User explicitly set reasoning_effort - use their value
finalReasoningEffort = request.reasoning_effort;
reasoningSource = "user-explicit";
// If user explicitly set reasoning_effort to something other than "none", consider thinking enabled
ccThinkingEnabled = finalReasoningEffort !== "none";
// Create reasoning object based on user's explicit setting
if (finalReasoningEffort === "none") {
modifiedRequest.reasoning = {
effort: "none",
enabled: false,
exclude: true
};
} else {
modifiedRequest.reasoning = {
effort: finalReasoningEffort,
enabled: true,
exclude: false
};
}
modifiedRequest.reasoning_effort = finalReasoningEffort;
} else if (request.reasoning && typeof request.reasoning === 'object') {
// CC sent reasoning parameter - check if enabled or disabled
const ccReasoning = request.reasoning;
if (ccReasoning.enabled !== false) {
// CC Thinking is ON → use transformer's configured reasoning_effort (default: "high")
finalReasoningEffort = this.reasoning_effort !== "none" ? this.reasoning_effort : "high";
reasoningSource = "claude-code-enabled";
ccThinkingEnabled = true;
// Create both formats for NanoGPT compatibility
modifiedRequest.reasoning = {
effort: finalReasoningEffort,
enabled: true,
exclude: false
};
modifiedRequest.reasoning_effort = finalReasoningEffort;
} else {
// CC Thinking is OFF (enabled=false) → set reasoning to disabled state
finalReasoningEffort = "none";
reasoningSource = "claude-code-disabled";
ccThinkingEnabled = false;
// Create reasoning object with explicit disable
modifiedRequest.reasoning = {
effort: "none",
enabled: false,
exclude: true
};
modifiedRequest.reasoning_effort = "none";
}
} else {
// No reasoning parameter from CC → CC Thinking is OFF (implicit)
finalReasoningEffort = "none";
reasoningSource = "claude-code-off";
ccThinkingEnabled = false;
// Create reasoning object with explicit disable
modifiedRequest.reasoning = {
effort: "none",
enabled: false,
exclude: true
};
modifiedRequest.reasoning_effort = "none";
}
// Validate reasoning_effort value
const validEfforts = ["none", "minimal", "low", "medium", "high"];
if (!validEfforts.includes(modifiedRequest.reasoning_effort)) {
modifiedRequest.reasoning_effort = "none";
modifiedRequest.reasoning = {
effort: "none",
enabled: false,
exclude: true
};
}
// Merge custom parameters from extra object ONLY if user explicitly set extra
if (request.extra !== undefined && this.extra && typeof this.extra === 'object' && Object.keys(this.extra).length > 0) {
// Debug: Check if extra object contains reasoning that would override CC Thinking
Object.assign(modifiedRequest, this.extra);
// Debug: Show reasoning state after extra merge
}
// Force reasoning injection for non-reasoning models
// This injects the FORCE_REASONING_PROMPT to make models think step-by-step
// Skip if the model is already a reasoning model (has built-in reasoning capabilities)
// Also skip if CC Thinking is OFF (ccThinkingEnabled is false)
if (this.enableForceReasoning && modifiedRequest.messages) {
const modelName = modifiedRequest.model || "";
if (isReasoningModel(modelName)) {
// Skip force reasoning for built-in reasoning models
} else if (!ccThinkingEnabled) {
// Skip force reasoning when CC Thinking is OFF
} else {
// Apply force reasoning - CC Thinking is ON and model is not a reasoning model
// Deep copy messages to avoid mutating the original
modifiedRequest.messages = JSON.parse(JSON.stringify(modifiedRequest.messages));
// Find existing system message
let systemMessage = modifiedRequest.messages.find((msg) => msg.role === "system");
// If system message exists and has array content, add reasoning prompt
if (Array.isArray(systemMessage?.content)) {
systemMessage.content.push({ type: "text", text: FORCE_REASONING_PROMPT });
} else if (systemMessage && typeof systemMessage.content === "string") {
// If system message has string content, convert to array and add prompt
systemMessage.content = [
{ type: "text", text: systemMessage.content },
{ type: "text", text: FORCE_REASONING_PROMPT }
];
}
// Get the last message in the conversation
let lastMessage = modifiedRequest.messages[modifiedRequest.messages.length - 1];
// If last message is from user and has array content, add reasoning prompt
if (lastMessage && lastMessage.role === "user" && Array.isArray(lastMessage.content)) {
lastMessage.content.push({ type: "text", text: FORCE_REASONING_PROMPT });
} else if (lastMessage && lastMessage.role === "user" && typeof lastMessage.content === "string") {
// If user message has string content, convert to array and add prompt
lastMessage.content = [
{ type: "text", text: lastMessage.content },
{ type: "text", text: FORCE_REASONING_PROMPT }
];
}
// If last message is from tool, add a new user message with reasoning prompt
if (lastMessage && lastMessage.role === "tool") {
modifiedRequest.messages.push({
role: "user",
content: [{ type: "text", text: FORCE_REASONING_PROMPT }]
});
}
// Mark that forceReasoning was applied for response processing
modifiedRequest.forceReasoningApplied = true;
}
}
// Update lastRequest with the modified version
this.lastRequest = modifiedRequest;
return modifiedRequest;
}
/**
* Transforms outgoing responses to convert reasoning to thinking format for Claude Code
* @async
* @param {Response} response - The Fetch API Response object from the LLM provider
* @returns {Promise<Response>} The transformed Response object with reasoning converted to thinking format
*/
async transformResponseOut(response) {
// If disabled, return response as-is
if (!this.enable) return response;
let responseToProcess = response;
// === ERROR INTERCEPTION (401/403/404/409/422/429/500) ===
// Intercept common HTTP errors and return friendly fake responses
// Return a friendly fake response instead of letting the error propagate
if (response.status === 401 || response.status === 403 || response.status === 404 ||
response.status === 409 || response.status === 422 || response.status === 429 ||
response.status === 500) {
const isStream = !!this.lastRequest?.stream;
const model = this.lastRequest?.model || "nanogpt-model";
let errorMessage = "";
// Generate appropriate error message based on status code
switch (response.status) {
case 401:
errorMessage = "⚠️ **Authentication Error**: Session required. Your API key is invalid or expired. Please check your configuration.";
break;
case 403:
errorMessage = "⚠️ **Forbidden**: Insufficient permissions. You don't have access to this resource or operation.";
break;
case 404:
errorMessage = "⚠️ **Not Found**: The requested resource was not found. Please check your request and try again.";
break;
case 409:
errorMessage = "⚠️ **Conflict**: Resource conflict detected. This could be due to duplicate creation or wrong state.";
break;
case 422:
errorMessage = "⚠️ **Invalid Input**: Validation failed. Please check your request parameters and format.";
break;
case 429:
errorMessage = "⚠️ **Rate Limited**: Too many requests. Please wait and try again later.";
break;
case 500:
errorMessage = "⚠️ **Internal Server Error**: The server encountered an unexpected error. Please try again later.";
break;
default:
errorMessage = `⚠️ **Error ${response.status}**: An unexpected error occurred. Please try again.`;
}
const id = generateId();
const created = Math.floor(Date.now() / 1000);
if (isStream) {
// Create SSE stream for error message
const streamLines = [
`data: ${JSON.stringify({
id: id,
object: "chat.completion.chunk",
created: created,
model: model,
choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }]
})}`,
`data: ${JSON.stringify({
id: id,
object: "chat.completion.chunk",
created: created,
model: model,
choices: [{ index: 0, delta: { content: errorMessage }, finish_reason: null }]
})}`,
`data: ${JSON.stringify({
id: id,
object: "chat.completion.chunk",
created: created,
model: model,
choices: [{ index: 0, delta: {}, finish_reason: "stop" }]
})}`,
"data: [DONE]"
];
return new Response(streamLines.join('\n\n'), {
status: 200,
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive"
}
});
} else {
// Create JSON response for error message
const fakeResponse = {
"id": id,
"object": "chat.completion",
"created": created,
"model": model,
"choices": [
{
"index": 0,
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": errorMessage
}
}
]
};
return new Response(JSON.stringify(fakeResponse), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
}
}
// Check if we should return fake response for max_tokens=1
// This is a workaround for models that don't handle max_tokens=1 correctly
// Claude Code uses max_tokens=1 when switching models via /model command
if (this.enableFakeResponse && this.lastRequest?.max_tokens === 1) {
const fakeResponse = createFakeResponse(this.lastRequest.model);
const finalResponse = new Response(JSON.stringify(fakeResponse), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
return finalResponse;
}
let transformedResponse = responseToProcess;
// Handle JSON responses (non-streaming) - TRANSFORM reasoning to thinking (if enabled)
if (responseToProcess.headers.get("Content-Type")?.includes("application/json")) {
transformedResponse = await handleNonStreamingResponse(
responseToProcess,
this.enableReasoningToThinking,
this.sanitizeToolSyntaxInReasoning,
this.sanitizeToolSyntaxInContent,
this.lastRequest?.forceReasoningApplied || false
);
}
// Handle streaming responses - TRANSFORM reasoning to thinking (if enabled)
else if (responseToProcess.headers.get("Content-Type")?.includes("stream")) {
transformedResponse = await handleStreamingResponse(
responseToProcess,
this.enableReasoningToThinking,
this.sanitizeToolSyntaxInReasoning,
this.sanitizeToolSyntaxInContent,
this.lastRequest?.forceReasoningApplied || false
);
}
// Return response as-is for other content types (or the transformed one)
return transformedResponse;
}
}
// ============================================================================
// GLOBAL FETCH INTERCEPTOR
// ============================================================================
/**
* Monkey-patch global fetch to intercept 401/429 errors from NanoGPT
* This is necessary because the router throws on non-2xx responses before the transformer can handle them
*/
(function patchFetch() {
if (globalThis._nanogpt_fetch_patched) return;
const originalFetch = globalThis.fetch;
globalThis.fetch = async function (url, options) {
const response = await originalFetch(url, options);
// Only intercept common HTTP errors
if (response.status !== 401 && response.status !== 403 && response.status !== 404 &&
response.status !== 409 && response.status !== 422 && response.status !== 429 &&
response.status !== 500) {
return response;
}
try {
// Clone response to inspect body without consuming the original
const clone = response.clone();
const text = await clone.text();
let errorData;
try {
errorData = JSON.parse(text);
} catch (e) {
return response; // Not JSON, ignore
}
// Check for specific error signatures
const isRateLimit = response.status === 429 &&
errorData?.error?.code === 'rate_limit_exceeded' &&
errorData?.error?.message?.includes('Too many authentication failures');
const isInvalidKey = response.status === 401 &&
errorData?.error?.code === 'invalid_api_key' &&
errorData?.error?.message === 'Invalid session';
const isForbidden = response.status === 403 &&
(errorData?.error?.code === 'insufficient_permissions' ||
errorData?.error?.code === 'forbidden' ||
errorData?.error?.message?.includes('permission'));
const isNotFound = response.status === 404 &&
(errorData?.error?.code === 'not_found' ||
errorData?.error?.message?.includes('not found'));
const isConflict = response.status === 409 &&
(errorData?.error?.code === 'conflict' ||
errorData?.error?.code === 'resource_conflict' ||
errorData?.error?.message?.includes('conflict'));
const isInvalidInput = response.status === 422 &&
(errorData?.error?.code === 'invalid_input' ||
errorData?.error?.code === 'validation_failed' ||
errorData?.error?.message?.includes('validation'));
const isInternalError = response.status === 500 &&
(errorData?.error?.code === 'internal_error' ||
errorData?.error?.code === 'server_error' ||
errorData?.error?.message?.includes('internal'));
if (isRateLimit || isInvalidKey || isForbidden || isNotFound ||
isConflict || isInvalidInput || isInternalError) {
// Extract request details to construct fake response
let model = "nanogpt-model";
let isStream = false;
if (options && options.body) {
try {
const body = JSON.parse(options.body);
if (body.model) model = body.model;
if (body.stream) isStream = body.stream;
} catch (e) {
// Ignore parsing error
}
}
// Generate appropriate error message based on error type
let errorMessage;
if (isInvalidKey) {
errorMessage = "⚠️ **Authentication Error**: Session required. Your API key is invalid or expired. Please check your configuration.";
} else if (isRateLimit) {
errorMessage = "⚠️ **Rate Limited**: Too many requests. Please wait and try again later.";
} else if (isForbidden) {
errorMessage = "⚠️ **Forbidden**: Insufficient permissions. You don't have access to this resource or operation.";
} else if (isNotFound) {
errorMessage = "⚠️ **Not Found**: The requested resource was not found. Please check your request and try again.";
} else if (isConflict) {
errorMessage = "⚠️ **Conflict**: Resource conflict detected. This could be due to duplicate creation or wrong state.";
} else if (isInvalidInput) {
errorMessage = "⚠️ **Invalid Input**: Validation failed. Please check your request parameters and format.";
} else if (isInternalError) {
errorMessage = "⚠️ **Internal Server Error**: The server encountered an unexpected error. Please try again later.";
} else {
errorMessage = `⚠️ **Error ${response.status}**: An unexpected error occurred. Please try again.`;
}
const id = "chatcmpl-" + Math.random().toString(36).substring(2, 15);
const created = Math.floor(Date.now() / 1000);
if (isStream) {
const streamLines = [
`data: ${JSON.stringify({
id: id,
object: "chat.completion.chunk",
created: created,
model: model,
choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }]
})}`,
`data: ${JSON.stringify({
id: id,
object: "chat.completion.chunk",
created: created,
model: model,
choices: [{ index: 0, delta: { content: errorMessage }, finish_reason: null }]
})}`,
`data: ${JSON.stringify({
id: id,
object: "chat.completion.chunk",
created: created,
model: model,
choices: [{ index: 0, delta: {}, finish_reason: "stop" }]
})}`,
"data: [DONE]"
];
return new Response(streamLines.join('\n\n'), {
status: 200,
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive"
}
});
} else {
const fakeResponse = {
"id": id,
"object": "chat.completion",
"created": created,
"model": model,
"choices": [
{
"index": 0,
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": errorMessage
}
}
]
};
return new Response(JSON.stringify(fakeResponse), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
}
}
} catch (e) {
// If anything goes wrong in interception, return original response
}
return response;
};
globalThis._nanogpt_fetch_patched = true;
})();
// Export the transformer for use in the router
module.exports = NanoGPTProductionTransformer;
require("fs"),require("path"),require("os");const e=["deepseek/deepseek-v3.2:thinking","deepseek-reasoner","deepseek-reasoner-cheaper","deepseek-r1","deepseek-ai/deepseek-v3.2-exp-thinking","deepseek-ai/DeepSeek-V3.1:thinking","deepseek-ai/DeepSeek-V3.1-Terminus:thinking","deepseek/deepseek-v3.2-speciale","moonshotai/kimi-k2-thinking","GLM-4.5-Air-Iceblink:thinking","GLM-4.5-Air-Steam-v1:thinking","z-ai/glm-4.6:thinking","zai-org/GLM-4.5-Air:thinking","THUDM/GLM-Z1-32B-0414","THUDM/GLM-Z1-9B-0414","zai-org/GLM-4.5:thinking","NousResearch/Hermes-4-70B:thinking","nousresearch/hermes-4-405b:thinking","Qwen/Qwen3-235B-A22B-Thinking-2507","qwen3-vl-235b-a22b-thinking","qwq-32b","qwen/qwq-32b-preview","qvq-max","pamanseau/OpenReasoning-Nemotron-32B","LLM360/K2-Think","tngtech/DeepSeek-TNG-R1T2-Chimera","tngtech/DeepSeek-R1T-Chimera","Steelskull/L3.3-Nevoria-R1-70b","Steelskull/L3.3-Electra-R1-70b","Steelskull/L3.3-Damascus-R1","inflatebot/MN-12B-Mag-Mell-R1","Steelskull/L3.3-Cu-Mai-R1-70b","Llama-3.3-70B-Electra-R1","Llama-3.3-70B-Vulpecula-R1","Llama-3.3-70B-Fallen-R1-v1","Llama-3.3-70B-Cu-Mai-R1","Llama-3.3-70B-Mokume-Gane-R1","huihui-ai/DeepSeek-R1-Distill-Qwen-32B-abliterated","huihui-ai/DeepSeek-R1-Distill-Llama-70B-abliterated","Alibaba-NLP/Tongyi-DeepResearch-30B-A3B","Envoid/Llama-3.05-Nemotron-Tenyxchat-Storybreaker-70B","Ling-Flash-2.0","MiniMax-M2","Salesforce/Llama-xLAM-2-70b-fc-r","deepcogito/cogito-v1-preview-qwen-32B","huihui-ai/Llama-3.1-Nemotron-70B-Instruct-HF-abliterated","inclusionai/ling-1t","meituan-longcat/LongCat-Flash-Chat-FP8","microsoft/MAI-DS-R1-FP8","minimax/minimax-01","nvidia/Llama-3.1-Nemotron-70B-Instruct-HF","nvidia/Llama-3.1-Nemotron-Ultra-253B-v1","nvidia/Llama-3.3-Nemotron-Super-49B-v1","nvidia/Llama-3_3-Nemotron-Super-49B-v1_5","nvidia/nvidia-nemotron-nano-9b-v2"],t="You are an expert reasoning model. \n\nAlways think step by step before answering. Even if the problem seems simple, always write down your reasoning process explicitly.\n\nOutput format:\n<reasoning_content>\nYour detailed thinking process goes here\n</reasoning_content>\nYour final answer must follow after the closing tag above.";function n(e){if("string"!=typeof e||!e)return e;let t=e;t.length;return t=t.replace(/<\|tool_calls_section_begin\|>/g,""),t=t.replace(/<\|tool_calls_section_end\|>/g,""),t=t.replace(/<\|tool_call_begin\|>/g,""),t=t.replace(/<\|tool_call_end\|>/g,""),t=t.replace(/<\|tool_call_argument_begin\|>/g,""),t=t.replace(/<\|tool_call_argument_end\|>/g,""),t=t.replace(/\s{2,}/g," "),t}function o(e){if("number"==typeof e)return{min:e,max:e,isRange:!1};if("string"!=typeof e)return null;const t=e.trim(),n=t.match(/^(-?\d+\.?\d*)\s*-\s*(-?\d+\.?\d*)$/);if(!n){const e=parseFloat(t);return isNaN(e)?null:{min:e,max:e,isRange:!1}}const o=parseFloat(n[1]),s=parseFloat(n[2]);if(isNaN(o)||isNaN(s))return null;return{min:Math.min(o,s),max:Math.max(o,s),isRange:!0}}function s(e){const t=o(e);return t?t.isRange?(n=t.min,s=t.max,paramName,Math.random()*(s-n)+n):t.min:null;var n,s}function i(e){return-99===e}function a(){let e="chatcmpl-";for(let t=0;t<14;t++)e+=Math.floor(10*Math.random());const t="abcdefghijklmnopqrstuvwxyz";for(let n=0;n<4;n++)e+=t.charAt(Math.floor(26*Math.random()));return e}function r(e,t,o,s){if(e.trim())if("data: [DONE]"!==e.trim())if(e.startsWith("data: "))try{const i=JSON.parse(e.slice(6)),a=i.choices?.[0],r=a?.delta||{},h=r.content;"string"==typeof h&&(h.includes("<|tool_calls_section_begin|>")&&(s.insidePseudoToolBlock=!0),h.includes("<|tool_calls_section_end|>")&&(s.insidePseudoToolBlock=!1),s.sanitizeToolSyntaxInContent?r.content=n(h):r.content=h,s.insidePseudoToolBlock?delete r.content:(r.content&&!s.hasTextContent&&(s.hasTextContent=!0),!r.content&&!s.hasTextContent&&s.reasoningBuffer&&h&&h.includes("<|tool_calls_section_end|>")&&(r.content="[Internal tool call removed; see Thinking for details.]",s.hasTextContent=!0),i.choices[0].delta=r));const d=i.choices?.[0]?.delta?.reasoning||i.choices?.[0]?.delta?.reasoning_content;if(d&&s.enableReasoningToThinking){const e=s.sanitizeToolSyntaxInReasoning?n(d):d;s.reasoningBuffer+=e;const a={...i,choices:[{...i.choices?.[0],delta:{...i.choices[0].delta,thinking:{content:e}}}]};a.choices?.[0]?.delta&&(delete a.choices[0].delta.reasoning,delete a.choices[0].delta.reasoning_content);const r=`data: ${JSON.stringify(a)}\n\n`;return void t.enqueue(o.encode(r))}if(s.enableReasoningToThinking&&i.choices?.[0]?.delta?.content&&s.reasoningBuffer&&!s.isReasoningFinished){s.isReasoningFinished=!0;const e=Date.now().toString(),n={...i,choices:[{...i.choices?.[0],delta:{...i.choices[0].delta,content:null,thinking:{content:s.reasoningBuffer,signature:e}}}]};n.choices?.[0]?.delta&&(delete n.choices[0].delta.reasoning,delete n.choices[0].delta.reasoning_content);const a=`data: ${JSON.stringify(n)}\n\n`;t.enqueue(o.encode(a))}if(s.enableReasoningToThinking&&(i.choices?.[0]?.delta?.reasoning&&delete i.choices[0].delta.reasoning,i.choices?.[0]?.delta?.reasoning_content&&delete i.choices[0].delta.reasoning_content),s.forceReasoningApplied&&s.enableReasoningToThinking){const e=i.choices?.[0]?.delta?.content;if("string"==typeof e){const n=function(e,t,n,o){const s=[];let i=n.forceReasoningPartialMatch+e;n.forceReasoningPartialMatch="";for(;i.length>0;)if("SEARCHING"===n.forceReasoningState){const e=i.indexOf(c);if(-1!==e)i=i.substring(e+c.length),n.forceReasoningState="REASONING";else{for(let e=c.length-1;e>0;e--)if(i.endsWith(c.substring(0,e))){n.forceReasoningPartialMatch=i.substring(i.length-e);break}i=""}}else if("REASONING"===n.forceReasoningState){const e=i.indexOf(l);if(-1!==e){const o=i.substring(0,e);if(o.length>0){n.forceReasoningBuffer+=o;const e={...t.choices[0].delta,thinking:{content:o}};delete e.content;const i={...t,choices:[{...t.choices[0],delta:e}]};s.push(`data: ${JSON.stringify(i)}\n\n`)}const a={...t.choices[0].delta,thinking:{signature:Date.now().toString()}};delete a.content;const r={...t,choices:[{...t.choices[0],delta:a}]};s.push(`data: ${JSON.stringify(r)}\n\n`),i=i.substring(e+l.length),n.forceReasoningState="FINAL"}else{let e=i;for(let t=l.length-1;t>0;t--)if(i.endsWith(l.substring(0,t))){n.forceReasoningPartialMatch=i.substring(i.length-t),e=i.substring(0,i.length-t);break}if(e.length>0){n.forceReasoningBuffer+=e;const o={...t.choices[0].delta,thinking:{content:e}};delete o.content;const i={...t,choices:[{...t.choices[0],delta:o}]};s.push(`data: ${JSON.stringify(i)}\n\n`)}i=""}}else if("FINAL"===n.forceReasoningState){if(i.length>0)if(/^\s*$/.test(i))n.forceReasoningAccumulatedWhitespace+=i;else{const e=n.forceReasoningAccumulatedWhitespace+i,o={...t.choices[0].delta,content:e};o.thinking&&delete o.thinking;const a={...t,choices:[{...t.choices[0],delta:o}]};s.push(`data: ${JSON.stringify(a)}\n\n`),n.forceReasoningAccumulatedWhitespace=""}i=""}return{chunks:s}}(e,i,s);if(n.chunks.length>0){for(const e of n.chunks)t.enqueue(o.encode(e));return}if("REASONING"===s.forceReasoningState||"SEARCHING"===s.forceReasoningState&&s.forceReasoningPartialMatch)return}}const u=`data: ${JSON.stringify(i)}\n\n`;t.enqueue(o.encode(u))}catch(n){t.enqueue(o.encode(e+"\n"))}else t.enqueue(o.encode(e+"\n"));else t.enqueue(o.encode(e+"\n"))}const c="<reasoning_content>",l="</reasoning_content>";async function h(e,t=!0,n=!1,o=!1,s=!1){if(!e.body)return e;const i=new TextDecoder,a=new TextEncoder,c={hasTextContent:!1,reasoningBuffer:"",isReasoningFinished:!1,enableReasoningToThinking:t,sanitizeToolSyntaxInReasoning:n,sanitizeToolSyntaxInContent:o,insidePseudoToolBlock:!1,forceReasoningApplied:s,forceReasoningState:"SEARCHING",forceReasoningBuffer:"",forceReasoningPartialMatch:"",forceReasoningAccumulatedWhitespace:""},l=new ReadableStream({start:t=>async function(e,t,n,o,s){const i=e.getReader();try{let e="";for(;;){const{done:a,value:c}=await i.read();if(a){if(e.trim()){const n=e.split("\n");for(const e of n)e.trim()&&r(e,t,o,s)}break}if(e+=n.decode(c,{stream:!0}),e.length>1e6){const n=e.split("\n");e=n.pop()||"";for(const e of n)e.trim()&&r(e,t,o,s);continue}const l=e.split("\n");e=l.pop()||"";for(const e of l)e.trim()&&r(e,t,o,s)}}catch(e){t.error(e)}finally{try{i.releaseLock()}catch(e){}t.close()}}(e.body,t,i,a,c)});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}!function(){if(globalThis._nanogpt_fetch_patched)return;const e=globalThis.fetch;globalThis.fetch=async function(t,n){const o=await e(t,n);if(401!==o.status&&403!==o.status&&404!==o.status&&409!==o.status&&422!==o.status&&429!==o.status&&500!==o.status)return o;try{const e=o.clone(),t=await e.text();let s;try{s=JSON.parse(t)}catch(e){return o}const i=429===o.status&&"rate_limit_exceeded"===s?.error?.code&&s?.error?.message?.includes("Too many authentication failures"),a=401===o.status&&"invalid_api_key"===s?.error?.code&&"Invalid session"===s?.error?.message,r=403===o.status&&("insufficient_permissions"===s?.error?.code||"forbidden"===s?.error?.code||s?.error?.message?.includes("permission")),c=404===o.status&&("not_found"===s?.error?.code||s?.error?.message?.includes("not found")),l=409===o.status&&("conflict"===s?.error?.code||"resource_conflict"===s?.error?.code||s?.error?.message?.includes("conflict")),h=422===o.status&&("invalid_input"===s?.error?.code||"validation_failed"===s?.error?.code||s?.error?.message?.includes("validation")),d=500===o.status&&("internal_error"===s?.error?.code||"server_error"===s?.error?.code||s?.error?.message?.includes("internal"));if(i||a||r||c||l||h||d){let e,t="nanogpt-model",s=!1;if(n&&n.body)try{const e=JSON.parse(n.body);e.model&&(t=e.model),e.stream&&(s=e.stream)}catch(e){}e=a?"⚠️ **Authentication Error**: Session required. Your API key is invalid or expired. Please check your configuration.":i?"⚠️ **Rate Limited**: Too many requests. Please wait and try again later.":r?"⚠️ **Forbidden**: Insufficient permissions. You don't have access to this resource or operation.":c?"⚠️ **Not Found**: The requested resource was not found. Please check your request and try again.":l?"⚠️ **Conflict**: Resource conflict detected. This could be due to duplicate creation or wrong state.":h?"⚠️ **Invalid Input**: Validation failed. Please check your request parameters and format.":d?"⚠️ **Internal Server Error**: The server encountered an unexpected error. Please try again later.":`⚠️ **Error ${o.status}**: An unexpected error occurred. Please try again.`;const u="chatcmpl-"+Math.random().toString(36).substring(2,15),g=Math.floor(Date.now()/1e3);if(s){const n=[`data: ${JSON.stringify({id:u,object:"chat.completion.chunk",created:g,model:t,choices:[{index:0,delta:{role:"assistant"},finish_reason:null}]})}`,`data: ${JSON.stringify({id:u,object:"chat.completion.chunk",created:g,model:t,choices:[{index:0,delta:{content:e},finish_reason:null}]})}`,`data: ${JSON.stringify({id:u,object:"chat.completion.chunk",created:g,model:t,choices:[{index:0,delta:{},finish_reason:"stop"}]})}`,"data: [DONE]"];return new Response(n.join("\n\n"),{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}{const n={id:u,object:"chat.completion",created:g,model:t,choices:[{index:0,finish_reason:"stop",message:{role:"assistant",content:e}}]};return new Response(JSON.stringify(n),{status:200,headers:{"Content-Type":"application/json"}})}}}catch(e){}return o},globalThis._nanogpt_fetch_patched=!0}(),module.exports=class{constructor(e){this.name="nanogpt",this.options=e,this.enable=this.options?.enable??!0,this.enableStreamOptions=this.options?.enableStreamOptions??!0,this.enableReasoningToThinking=this.options?.enableReasoningToThinking??!0,this.enableFakeResponse=this.options?.enableFakeResponse??!0,this.enableForceReasoning=this.options?.enableForceReasoning??!1,this.temperature=this.options?.temperature??.1,this.max_tokens=this.options?.max_tokens??-99,this.top_p=this.options?.top_p??.95,this.frequency_penalty=this.options?.frequency_penalty??0,this.presence_penalty=this.options?.presence_penalty??0,this.parallel_tool_calls=this.options?.parallel_tool_calls??!0,this.top_k=this.options?.top_k??40,this.repetition_penalty=this.options?.repetition_penalty??1.15,this.cache_control=this.options?.cache_control??null,this.reasoning_effort=this.options?.reasoning_effort??"none",this._rangeConfigs={temperature:o(this.temperature),max_tokens:o(this.max_tokens),top_p:o(this.top_p),frequency_penalty:o(this.frequency_penalty),presence_penalty:o(this.presence_penalty),parallel_tool_calls:o(this.parallel_tool_calls),top_k:o(this.top_k),repetition_penalty:o(this.repetition_penalty)},this.sanitizeToolSyntaxInReasoning=this.options?.sanitizeToolSyntaxInReasoning??!1,this.sanitizeToolSyntaxInContent=this.options?.sanitizeToolSyntaxInContent??!1,this.extra=this.options?.extra??{},this.lastRequest=null}async transformRequestIn(n){if(!this.enable)return n;this.lastRequest={...n};const o={...n};if(this.enableStreamOptions&&(o.stream_options={include_usage:!0,...o.stream_options}),!i(this.temperature)){const e=s(this.temperature);null!==e&&(o.temperature=e)}const a=1===n.max_tokens,r=i(this.max_tokens);if(a)o.max_tokens=n.max_tokens;else if(r);else{const e=s(this.max_tokens);null!==e&&(o.max_tokens=Math.round(e))}if(!i(this.top_p)){const e=s(this.top_p);null!==e&&(o.top_p=e)}if(!i(this.frequency_penalty)){const e=s(this.frequency_penalty);null!==e&&(o.frequency_penalty=e)}if(!i(this.presence_penalty)){const e=s(this.presence_penalty);null!==e&&(o.presence_penalty=e)}if(void 0!==n.parallel_tool_calls){const e=s(this.parallel_tool_calls);null!==e&&(o.parallel_tool_calls=Boolean(e))}if(void 0!==n.top_k&&null!==this.top_k&&!i(this.top_k)){const e=s(this.top_k);null!==e&&(o.top_k=Math.round(e))}if(void 0!==n.repetition_penalty){const e=s(this.repetition_penalty);null!==e&&(o.repetition_penalty=e)}void 0!==n.cache_control&&this.cache_control&&this.cache_control.enabled&&(o.cache_control=this.cache_control);let c=this.reasoning_effort,l="configuration",h=!1;if("reasoning_effort"in n)c=n.reasoning_effort,l="user-explicit",h="none"!==c,o.reasoning="none"===c?{effort:"none",enabled:!1,exclude:!0}:{effort:c,enabled:!0,exclude:!1},o.reasoning_effort=c;else if(n.reasoning&&"object"==typeof n.reasoning){!1!==n.reasoning.enabled?(c="none"!==this.reasoning_effort?this.reasoning_effort:"high",l="claude-code-enabled",h=!0,o.reasoning={effort:c,enabled:!0,exclude:!1},o.reasoning_effort=c):(c="none",l="claude-code-disabled",h=!1,o.reasoning={effort:"none",enabled:!1,exclude:!0},o.reasoning_effort="none")}else c="none",l="claude-code-off",h=!1,o.reasoning={effort:"none",enabled:!1,exclude:!0},o.reasoning_effort="none";if(["none","minimal","low","medium","high"].includes(o.reasoning_effort)||(o.reasoning_effort="none",o.reasoning={effort:"none",enabled:!1,exclude:!0}),void 0!==n.extra&&this.extra&&"object"==typeof this.extra&&Object.keys(this.extra).length>0&&Object.assign(o,this.extra),this.enableForceReasoning&&o.messages){if(function(t){if(!t)return!1;const n=t.toLowerCase();return!!e.some((e=>e.toLowerCase()===n))||!["z-ai/glm-4.6","GLM-4.5-Air-Iceblink","GLM-4.5-Air-Steam-v1","deepseek/deepseek-v3.2","deepseek-ai/DeepSeek-V3.1","moonshotai/kimi-k2-instruct","NousResearch/Hermes-4-70B","nousresearch/hermes-4-405b","qwen3-vl-235b-a22b-instruct","Qwen/Qwen3-235B-A22B"].some((e=>e.toLowerCase()===n))&&[":thinking","-thinking","-r1","reasoner","think","qwq","qvq"].some((e=>n.includes(e)))}(o.model||""));else if(h){o.messages=JSON.parse(JSON.stringify(o.messages));let e=o.messages.find((e=>"system"===e.role));Array.isArray(e?.content)?e.content.push({type:"text",text:t}):e&&"string"==typeof e.content&&(e.content=[{type:"text",text:e.content},{type:"text",text:t}]);let n=o.messages[o.messages.length-1];n&&"user"===n.role&&Array.isArray(n.content)?n.content.push({type:"text",text:t}):n&&"user"===n.role&&"string"==typeof n.content&&(n.content=[{type:"text",text:n.content},{type:"text",text:t}]),n&&"tool"===n.role&&o.messages.push({role:"user",content:[{type:"text",text:t}]}),o.forceReasoningApplied=!0}else;}return this.lastRequest=o,o}async transformResponseOut(e){if(!this.enable)return e;let t=e;if(401===e.status||403===e.status||404===e.status||409===e.status||422===e.status||429===e.status||500===e.status){const t=!!this.lastRequest?.stream,n=this.lastRequest?.model||"nanogpt-model";let o="";switch(e.status){case 401:o="⚠️ **Authentication Error**: Session required. Your API key is invalid or expired. Please check your configuration.";break;case 403:o="⚠️ **Forbidden**: Insufficient permissions. You don't have access to this resource or operation.";break;case 404:o="⚠️ **Not Found**: The requested resource was not found. Please check your request and try again.";break;case 409:o="⚠️ **Conflict**: Resource conflict detected. This could be due to duplicate creation or wrong state.";break;case 422:o="⚠️ **Invalid Input**: Validation failed. Please check your request parameters and format.";break;case 429:o="⚠️ **Rate Limited**: Too many requests. Please wait and try again later.";break;case 500:o="⚠️ **Internal Server Error**: The server encountered an unexpected error. Please try again later.";break;default:o=`⚠️ **Error ${e.status}**: An unexpected error occurred. Please try again.`}const s=a(),i=Math.floor(Date.now()/1e3);if(t){const e=[`data: ${JSON.stringify({id:s,object:"chat.completion.chunk",created:i,model:n,choices:[{index:0,delta:{role:"assistant"},finish_reason:null}]})}`,`data: ${JSON.stringify({id:s,object:"chat.completion.chunk",created:i,model:n,choices:[{index:0,delta:{content:o},finish_reason:null}]})}`,`data: ${JSON.stringify({id:s,object:"chat.completion.chunk",created:i,model:n,choices:[{index:0,delta:{},finish_reason:"stop"}]})}`,"data: [DONE]"];return new Response(e.join("\n\n"),{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}{const e={id:s,object:"chat.completion",created:i,model:n,choices:[{index:0,finish_reason:"stop",message:{role:"assistant",content:o}}]};return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json"}})}}if(this.enableFakeResponse&&1===this.lastRequest?.max_tokens){const e=(o=this.lastRequest.model,{id:a(),object:"chat.completion",created:Math.floor(Date.now()/1e3),model:o,choices:[{index:0,finish_reason:"length",message:{role:"assistant",content:"\n"}}]});return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json"}})}var o;let s=t;return t.headers.get("Content-Type")?.includes("application/json")?s=await async function(e,t=!0,o=!1,s=!1,i=!1){const a=await e.json();if(t&&a.choices&&Array.isArray(a.choices))for(const e of a.choices){if(!e.message)continue;if(s&&"string"==typeof e.message.content){let t=e.message.content;const o=t.length;t="string"==typeof(r=t)&&r?r.replace(/<\|tool_calls_section_begin\|>[\s\S]*?<\|tool_calls_section_end\|>/g,""):r,t=n(t),""===t.trim()&&o>0&&(t="[Internal tool call removed; see Thinking for details.]"),e.message.content=t}const t=e.message.reasoning||e.message.reasoning_content;if(t){const s=o?n(t):t;e.message.thinking={content:s,signature:Date.now().toString()},delete e.message.reasoning,delete e.message.reasoning_content}if(i&&"string"==typeof e.message.content&&!e.message.thinking){const t=/<reasoning_content>([\s\S]*?)<\/reasoning_content>/,s=e.message.content.match(t);if(s&&s[1]){const t=s[1].trim(),i=o?n(t):t;e.message.thinking={content:i,signature:Date.now().toString()},e.message.content=e.message.content.replace(/<reasoning_content>[\s\S]*?<\/reasoning_content>/,"").trim()}}}var r;return new Response(JSON.stringify(a),{status:e.status,statusText:e.statusText,headers:e.headers})}(t,this.enableReasoningToThinking,this.sanitizeToolSyntaxInReasoning,this.sanitizeToolSyntaxInContent,this.lastRequest?.forceReasoningApplied||!1):t.headers.get("Content-Type")?.includes("stream")&&(s=await h(t,this.enableReasoningToThinking,this.sanitizeToolSyntaxInReasoning,this.sanitizeToolSyntaxInContent,this.lastRequest?.forceReasoningApplied||!1)),s}};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment