{"uid":"cap_aHSZBN9TWMSRLOdpabpdW","slug":"x402-gateway-production-up-railway-app-b9cd3b75","name":"DeepSeek V3.2 LLM API (x402 Gateway)","description":"DeepSeek's latest flagship model — improved reasoning and coding over V3 at same low cost","url":"https://x402-gateway-production.up.railway.app/api/llm/deepseek-v3.2","method":"POST","headers":{},"bodySchema":null,"responseSchema":null,"example":{"request":{"model":"deepseek-v3.2","messages":[{"role":"user","content":"Write a Python function that parses a nested JSON object and flattens it into a single-level dictionary. Include comments explaining the logic and handle edge cases like empty objects and null values."}],"max_tokens":1000,"temperature":0.7},"response":{"model":"deepseek/deepseek-v3.2-20251201","usage":{"cost":0.0003826116,"is_byok":false,"cost_details":{"upstream_inference_cost":0.0003826116,"upstream_inference_prompt_cost":0.0000046116,"upstream_inference_completions_cost":0.000378},"total_tokens":1048,"prompt_tokens":48,"completion_tokens":1000,"prompt_tokens_details":{"audio_tokens":0,"video_tokens":0,"cached_tokens":33,"cache_write_tokens":0},"completion_tokens_details":{"audio_tokens":0,"image_tokens":0,"reasoning_tokens":0}},"content":"Here's a Python function that flattens nested JSON objects with detailed comments and edge case handling:\n\n```python\nimport json\nfrom typing import Dict, Any, Optional\n\ndef flatten_json(nested_dict: Dict[str, Any], \n                 parent_key: str = '', \n                 sep: str = '_') -> Dict[str, Any]:\n    \"\"\"\n    Recursively flattens a nested JSON/dictionary object into a single-level dictionary.\n    \n    Args:\n        nested_dict: The nested dictionary/JSON object to flatten\n        parent_key: The base key for the current recursion level (used internally)\n        sep: Separator to use between nested keys (default is '_')\n    \n    Returns:\n        A flattened single-level dictionary\n        \n    Examples:\n        >>> nested = {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}}\n        >>> flatten_json(nested)\n        {'a': 1, 'b_c': 2, 'b_d_e': 3}\n    \"\"\"\n    items = {}\n    \n    # Edge case: Handle None or empty input\n    if nested_dict is None:\n        return {}\n    \n    if not isinstance(nested_dict, dict):\n        raise TypeError(\"Input must be a dictionary or JSON object\")\n    \n    # Edge case: Handle empty dictionary\n    if not nested_dict:\n        return {}\n    \n    for key, value in nested_dict.items():\n        # Create the new key by combining parent key and current key\n        new_key = f\"{parent_key}{sep}{key}\" if parent_key else key\n        \n        # Handle different types of values\n        if isinstance(value, dict) and value:\n            # Recursively flatten nested dictionaries\n            items.update(flatten_json(value, new_key, sep))\n        elif isinstance(value, list):\n            # Handle lists by converting them to indexed keys\n            for i, item in enumerate(value):\n                list_key = f\"{new_key}{sep}{i}\"\n                if isinstance(item, dict):\n                    items.update(flatten_json(item, list_key, sep))\n                else:\n                    items[list_key] = item\n        else:\n            # Handle primitive values (including None, strings, numbers, booleans)\n            # Note: None values are preserved in the output\n            items[new_key] = value\n    \n    return items\n\n\ndef flatten_json_safe(nested_dict: Dict[str, Any], \n                      sep: str = '_',\n                      max_depth: int = 10) -> Optional[Dict[str, Any]]:\n    \"\"\"\n    A safer version with depth limiting and more robust error handling.\n    \n    Args:\n        nested_dict: The nested dictionary/JSON object to flatten\n        sep: Separator to use between nested keys\n        max_depth: Maximum recursion depth to prevent stack overflow\n    \n    Returns:\n        Flattened dictionary or None if error occurs\n    \"\"\"\n    def _flatten_recursive(current_dict: Dict[str, Any], \n                          parent_key: str = '', \n                          current_depth: int = 0) -> Dict[str, Any]:\n        \"\"\"Inner recursive function with depth checking.\"\"\"\n        # Prevent infinite recursion\n        if current_depth >= max_depth:\n            raise RecursionError(f\"Maximum recursion depth ({max_depth}) exceeded\")\n        \n        items = {}\n        \n        for key, value in current_dict.items():\n            new_key = f\"{parent_key}{sep}{key}\" if parent_key else key\n            \n            if isinstance(value, dict) and value:\n                items.update(_flatten_recursive(value, new_key, current_depth + 1))\n            elif isinstance(value, list):\n                for i, item in enumerate(value):\n                    list_key = f\"{new_key}{sep}{i}\"\n                    if isinstance(item, dict):\n                        items.update(_flatten_recursive(item, list_key, current_depth + 1))\n                    else:\n                        items[list_key] = item\n            else:\n                items[new_key] = value\n        \n        return items\n    \n    try:\n        # Handle edge cases\n        if nested_dict is None:\n            return {}\n        \n        if not isinstance(nested_dict, dict):\n            raise TypeError(\"Input must be a dictionary\")\n        \n        return _flatten_recursive(nested_dict, '', 0)\n    \n    except (RecursionError, TypeError) as e:\n        print(f\"Error flattening JSON: {e}\")\n        return None\n\n\n# Example usage and demonstration\nif __name__ == \"__main__\":\n    # Test cases demonstrating various edge cases\n    \n    # Example 1: Basic nested JSON\n    sample_json = {\n        \"name\": \"John\",\n        \"age\": 30,\n        \"address\": {\n            \"street\": \"123 Main St\",\n            \"city\": \"New York\",\n            \"coordinates\": {\n                \"lat\": 40.7128,\n                \"lng\": -"}},"exampleRequest":{"model":"deepseek-v3.2","messages":[{"role":"user","content":"Write a Python function that parses a nested JSON object and flattens it into a single-level dictionary. Include comments explaining the logic and handle edge cases like empty objects and null values."}],"max_tokens":1000,"temperature":0.7},"tags":["x402"],"displayCostAmount":"0.005","displayCostAsset":"USDC","priceDynamic":false,"priceHint":null,"priceStatus":"priced","priceSource":"settled","requiresHandshake":false,"reviewCount":0,"rating":{"score":"0.00","successRate":"0.10","reviews":0,"stars":null,"state":"rated"},"availabilityStatus":"unknown","priceObserved":null,"sessionDeposit":null,"pricing":{"kind":"static","summary":"$0.005/call","primary":{"kind":"static","protocol":"x402","network":"base","amountUsd":"0.005","per":"call","confidence":"exact"},"accepted":[{"kind":"static","protocol":"x402","network":"base","amountUsd":"0.005","per":"call","confidence":"exact"}]},"paymentMethods":[{"uid":"pm_UzvZtJFrnMByG2tbf0HGF","protocol":"x402","methodType":"crypto","chain":"base","mode":"charge","costAmount":"0.005","costPer":"request","priority":0,"asset":null,"unit":"request","depositMicros":null,"planRef":null}],"brandName":null,"brandSlug":null,"brandBaseUrl":null,"brandDocsUrl":null,"whatItDoes":"Calls DeepSeek's latest V3.2 flagship language model for improved reasoning and coding tasks, billed per-call via x402 micropayment","exampleAgentPrompt":"Use DeepSeek V3.2 to write a Python function that parses a nested JSON object and flattens it into a single-level dictionary — I need clean, well-commented code with edge case handling.","exampleUseCases":null,"resultDescription":"Returns a text completion from DeepSeek V3.2, which may include natural language responses, reasoning chains, or code snippets depending on the prompt. Billed at $0.005 USDC per call via x402 protocol.","failureModes":["Payment failure if x402 USDC balance is insufficient","Model unavailable or overloaded returning 503","Malformed request body returns 400 with validation error","Prompt too long exceeds context window limit","Network timeout on long-form generation requests"],"whenToPreferThis":"Prefer this endpoint when you need DeepSeek V3.2 specifically — offering improved reasoning and coding over V3 — at a low per-call cost of $0.005 USDC. Ideal for agents doing code generation or multi-step reasoning tasks who want a cost-effective alternative to OpenAI models. Use over DeepSeek V3 when improved reasoning quality matters; use over GPT-4o when cost is a primary concern.","instructions":null,"reviewSummary":null,"reviewSummaryHighlights":null,"reviewSummaryConcerns":null,"reviewSummaryGeneratedAt":null,"activationCount":10,"lastUsedAt":"2026-06-17T22:03:45.622Z","lastSuccessfullyRanAt":"2026-06-17T21:55:18.039Z","lastHealthCheckAt":"2026-09-15T06:50:09.277Z","isFirstParty":false}