curl -X POST "https://api.tensorone.ai/v2/ai/code-generation" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Create a function that implements binary search on a sorted array",
    "language": "python",
    "model": "codellama-34b", 
    "taskType": "generation",
    "style": "clean",
    "includeComments": true,
    "includeTests": true
  }'
{
  "generatedCode": "def binary_search(arr, target):\n    \"\"\"\n    Perform binary search on a sorted array.\n    \n    Args:\n        arr (list): Sorted array to search in\n        target: Element to search for\n    \n    Returns:\n        int: Index of target if found, -1 otherwise\n    \"\"\"\n    left, right = 0, len(arr) - 1\n    \n    while left <= right:\n        mid = (left + right) // 2\n        \n        if arr[mid] == target:\n            return mid\n        elif arr[mid] < target:\n            left = mid + 1\n        else:\n            right = mid - 1\n    \n    return -1",
  "language": "python",
  "explanation": "This function implements binary search algorithm to find a target element in a sorted array. It uses the divide-and-conquer approach, repeatedly dividing the search space in half until the target is found or the search space is exhausted.",
  "tests": "import unittest\n\nclass TestBinarySearch(unittest.TestCase):\n    def setUp(self):\n        self.sorted_array = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]\n    \n    def test_found_element(self):\n        self.assertEqual(binary_search(self.sorted_array, 7), 3)\n        self.assertEqual(binary_search(self.sorted_array, 1), 0)\n        self.assertEqual(binary_search(self.sorted_array, 19), 9)\n    \n    def test_not_found_element(self):\n        self.assertEqual(binary_search(self.sorted_array, 4), -1)\n        self.assertEqual(binary_search(self.sorted_array, 20), -1)\n    \n    def test_empty_array(self):\n        self.assertEqual(binary_search([], 5), -1)\n\nif __name__ == '__main__':\n    unittest.main()",
  "suggestions": [
    "Consider adding type hints for better code documentation",
    "Add input validation to ensure the array is sorted",
    "Consider using bisect module for built-in binary search functionality"
  ],
  "dependencies": [],
  "complexity": {
    "timeComplexity": "O(log n)",
    "spaceComplexity": "O(1)",
    "cyclomaticComplexity": 4
  },
  "metadata": {
    "model": "codellama-34b",
    "tokensGenerated": 245,
    "generationTime": 2.3
  }
}
Generate high-quality code in multiple programming languages using AI models specifically trained on code datasets. Perfect for code completion, function generation, debugging, and automated refactoring.

Request Body

prompt
string
required
Description of the code you want to generate. Can be natural language or partial code.
language
string
required
Programming language for code generation:
  • python - Python 3.x
  • javascript - JavaScript (ES6+)
  • typescript - TypeScript
  • java - Java 8+
  • cpp - C++
  • c - C
  • csharp - C#
  • go - Go
  • rust - Rust
  • php - PHP
  • ruby - Ruby
  • swift - Swift
  • kotlin - Kotlin
  • scala - Scala
  • r - R
  • sql - SQL
  • bash - Bash/Shell
  • html - HTML/CSS
model
string
default:"codellama-34b"
Code generation model to use:
  • codellama-34b - Meta’s Code Llama, best for general code generation
  • codellama-70b - Larger model, highest quality but slower
  • starcoder-15b - BigCode’s StarCoder, good for completion
  • wizardcoder-34b - WizardCoder, excellent for complex logic
  • phind-codellama-34b - Fine-tuned for problem-solving
  • deepseek-coder-33b - Specialized for multiple languages
taskType
string
default:"generation"
Type of code task:
  • generation - Generate code from description
  • completion - Complete partial code
  • explanation - Explain existing code
  • debugging - Find and fix bugs
  • refactoring - Improve code structure
  • testing - Generate unit tests
  • documentation - Generate code documentation
context
string
Additional context or existing code that relates to the generation task
style
string
default:"clean"
Code style preference:
  • clean - Clean, readable code with good practices
  • minimal - Minimal, concise code
  • verbose - Well-commented, explanatory code
  • enterprise - Enterprise-style with extensive error handling
  • functional - Functional programming style where applicable
includeComments
boolean
default:"true"
Whether to include explanatory comments in the generated code
includeTests
boolean
default:"false"
Whether to generate unit tests along with the code
maxTokens
integer
default:"2000"
Maximum number of tokens to generate (100-4000)
temperature
number
default:"0.1"
Creativity level (0.0-1.0). Lower values produce more deterministic code.

Response

generatedCode
string
The generated code
language
string
Programming language of the generated code
explanation
string
Human-readable explanation of what the code does
tests
string
Generated unit tests (if requested)
suggestions
array
Code improvement suggestions and alternative approaches
dependencies
array
Required libraries, packages, or imports
complexity
object
Code complexity analysis
metadata
object
Generation metadata

Example

curl -X POST "https://api.tensorone.ai/v2/ai/code-generation" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Create a function that implements binary search on a sorted array",
    "language": "python",
    "model": "codellama-34b", 
    "taskType": "generation",
    "style": "clean",
    "includeComments": true,
    "includeTests": true
  }'
{
  "generatedCode": "def binary_search(arr, target):\n    \"\"\"\n    Perform binary search on a sorted array.\n    \n    Args:\n        arr (list): Sorted array to search in\n        target: Element to search for\n    \n    Returns:\n        int: Index of target if found, -1 otherwise\n    \"\"\"\n    left, right = 0, len(arr) - 1\n    \n    while left <= right:\n        mid = (left + right) // 2\n        \n        if arr[mid] == target:\n            return mid\n        elif arr[mid] < target:\n            left = mid + 1\n        else:\n            right = mid - 1\n    \n    return -1",
  "language": "python",
  "explanation": "This function implements binary search algorithm to find a target element in a sorted array. It uses the divide-and-conquer approach, repeatedly dividing the search space in half until the target is found or the search space is exhausted.",
  "tests": "import unittest\n\nclass TestBinarySearch(unittest.TestCase):\n    def setUp(self):\n        self.sorted_array = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]\n    \n    def test_found_element(self):\n        self.assertEqual(binary_search(self.sorted_array, 7), 3)\n        self.assertEqual(binary_search(self.sorted_array, 1), 0)\n        self.assertEqual(binary_search(self.sorted_array, 19), 9)\n    \n    def test_not_found_element(self):\n        self.assertEqual(binary_search(self.sorted_array, 4), -1)\n        self.assertEqual(binary_search(self.sorted_array, 20), -1)\n    \n    def test_empty_array(self):\n        self.assertEqual(binary_search([], 5), -1)\n\nif __name__ == '__main__':\n    unittest.main()",
  "suggestions": [
    "Consider adding type hints for better code documentation",
    "Add input validation to ensure the array is sorted",
    "Consider using bisect module for built-in binary search functionality"
  ],
  "dependencies": [],
  "complexity": {
    "timeComplexity": "O(log n)",
    "spaceComplexity": "O(1)",
    "cyclomaticComplexity": 4
  },
  "metadata": {
    "model": "codellama-34b",
    "tokensGenerated": 245,
    "generationTime": 2.3
  }
}

Code Completion

Complete partial code snippets:
Python
# Complete partial code
completion_result = requests.post(
    "https://api.tensorone.ai/v2/ai/code-generation",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "prompt": "def fibonacci(n):\n    if n <= 1:\n        return n\n    # Complete this function",
        "language": "python",
        "taskType": "completion",
        "context": "Implement fibonacci sequence using dynamic programming",
        "style": "clean"
    }
)

print("Completed Code:")
print(completion_result.json()['generatedCode'])

Code Debugging

Find and fix bugs in existing code:
Python
# Debug code with issues
debug_result = requests.post(
    "https://api.tensorone.ai/v2/ai/code-generation",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "prompt": """
        def divide_numbers(a, b):
            result = a / b
            return result
        
        # This code has potential issues, please fix them
        """,
        "language": "python",
        "taskType": "debugging",
        "style": "enterprise"
    }
)

result = debug_result.json()
print("Fixed Code:")
print(result['generatedCode'])
print("\nIssues Found:")
print(result['explanation'])

Code Refactoring

Improve existing code structure and readability:
Python
# Refactor messy code
refactor_result = requests.post(
    "https://api.tensorone.ai/v2/ai/code-generation",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "prompt": """
        def calc(x,y,z):
            if z=='add':return x+y
            elif z=='sub':return x-y
            elif z=='mul':return x*y
            elif z=='div':return x/y if y!=0 else 'error'
        """,
        "language": "python",
        "taskType": "refactoring",
        "style": "clean",
        "includeComments": True
    }
)

result = refactor_result.json()
print("Refactored Code:")
print(result['generatedCode'])

Multi-Language Projects

Generate code for full-stack applications:
Python
def generate_fullstack_component(feature_description):
    """Generate frontend and backend code for a feature"""
    
    # Generate backend API
    backend_result = requests.post(
        "https://api.tensorone.ai/v2/ai/code-generation",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        json={
            "prompt": f"Create a REST API endpoint for {feature_description}",
            "language": "python",
            "context": "Using Flask framework with SQLAlchemy",
            "style": "enterprise",
            "includeTests": True
        }
    )
    
    # Generate frontend component
    frontend_result = requests.post(
        "https://api.tensorone.ai/v2/ai/code-generation", 
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        json={
            "prompt": f"Create a React component for {feature_description}",
            "language": "javascript",
            "context": "Using React hooks and axios for API calls",
            "style": "clean",
            "includeComments": True
        }
    )
    
    return {
        "backend": backend_result.json(),
        "frontend": frontend_result.json()
    }

# Generate user registration feature
components = generate_fullstack_component("user registration with email validation")
print("Backend API:")
print(components["backend"]["generatedCode"])
print("\nFrontend Component:")
print(components["frontend"]["generatedCode"])

Advanced Features

Context-Aware Generation

Provide existing codebase context for better integration:
Python
context_aware_generation = requests.post(
    "https://api.tensorone.ai/v2/ai/code-generation",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "prompt": "Add a method to calculate user statistics",
        "language": "python",
        "context": """
        class User:
            def __init__(self, name, email, age):
                self.name = name
                self.email = email
                self.age = age
                self.login_count = 0
                self.last_login = None
        """,
        "taskType": "generation",
        "style": "clean"
    }
)

Code Documentation Generation

Generate comprehensive documentation:
Python
doc_generation = requests.post(
    "https://api.tensorone.ai/v2/ai/code-generation",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "prompt": """
        def merge_sort(arr):
            if len(arr) <= 1:
                return arr
            
            mid = len(arr) // 2
            left = merge_sort(arr[:mid])
            right = merge_sort(arr[mid:])
            
            return merge(left, right)
        """,
        "language": "python",
        "taskType": "documentation",
        "style": "verbose"
    }
)

print("Generated Documentation:")
print(doc_generation.json()['generatedCode'])

Batch Code Generation

Generate multiple related functions:
Python
def batch_generate_code(prompts, language="python"):
    results = []
    
    for prompt in prompts:
        response = requests.post(
            "https://api.tensorone.ai/v2/ai/code-generation",
            headers={"Authorization": "Bearer YOUR_API_KEY"},
            json={
                "prompt": prompt,
                "language": language,
                "model": "codellama-34b",
                "style": "clean",
                "includeComments": True
            }
        )
        results.append(response.json())
    
    return results

# Generate a complete data structure
prompts = [
    "Implement a Node class for a linked list",
    "Implement a LinkedList class with add, remove, and find methods",
    "Add a method to reverse the linked list",
    "Add a method to find the middle element of the linked list"
]

results = batch_generate_code(prompts)
for i, result in enumerate(results):
    print(f"Function {i+1}:")
    print(result['generatedCode'])
    print()

Code Quality Analysis

Get detailed analysis of generated code:
Python
# Generate code with quality analysis
quality_result = requests.post(
    "https://api.tensorone.ai/v2/ai/code-generation",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "prompt": "Create a function to validate email addresses using regex",
        "language": "python",
        "taskType": "generation",
        "style": "enterprise",
        "includeComments": True,
        "analyzeQuality": True
    }
)

result = quality_result.json()
print("Generated Code:")
print(result['generatedCode'])

print("\nQuality Analysis:")
print(f"Time Complexity: {result['complexity']['timeComplexity']}")
print(f"Cyclomatic Complexity: {result['complexity']['cyclomaticComplexity']}")
print("\nSuggestions:")
for suggestion in result['suggestions']:
    print(f"- {suggestion}")

Programming Language Specific Features

Python

  • Type hints and docstrings
  • PEP 8 compliance
  • Async/await patterns
  • Context managers

JavaScript/TypeScript

  • ES6+ features
  • React/Vue/Angular patterns
  • Node.js backend patterns
  • TypeScript interfaces

Java

  • Spring Boot patterns
  • Exception handling
  • Design patterns
  • JUnit test generation

SQL

  • Query optimization
  • Index suggestions
  • Database schema design
  • Stored procedures

Use Cases

Development Acceleration

  • Boilerplate Generation: Create repetitive code structures
  • API Development: Generate REST/GraphQL endpoints
  • Test Creation: Automated unit and integration tests
  • Database Queries: Complex SQL generation

Learning and Education

  • Code Examples: Generate examples for tutorials
  • Algorithm Implementation: Learn different approaches
  • Best Practices: See well-structured code patterns
  • Code Review: Get suggestions for improvements

Legacy Code Modernization

  • Migration: Convert code between languages/frameworks
  • Refactoring: Improve old code structures
  • Documentation: Add missing documentation
  • Testing: Add tests to legacy code

Best Practices

Effective Prompts

  • Be Specific: Include requirements, constraints, and expected behavior
  • Provide Context: Share related code or system architecture
  • Specify Style: Mention coding standards or preferences
  • Include Examples: Show input/output examples when relevant

Code Quality

  • Review Generated Code: Always review and test generated code
  • Add Context: Provide existing codebase patterns for consistency
  • Security Review: Check for security vulnerabilities
  • Performance Consideration: Analyze complexity and optimization needs

Integration

  • Version Control: Track generated code changes
  • Testing: Thoroughly test generated code
  • Documentation: Maintain documentation for generated components
  • Team Review: Have team members review significant generations

Pricing

  • Basic Generation: $0.01 per 1K tokens generated
  • Advanced Models: $0.02 per 1K tokens (70B+ parameter models)
  • Code Analysis: Additional $0.005 per analysis
  • Batch Processing: 15% discount for 100+ generations
  • Enterprise: Custom pricing for high-volume usage
Code generation typically completes in 2-10 seconds depending on complexity and model size. Longer or more complex requests may take up to 30 seconds.
For best results, provide specific requirements, expected input/output, and any relevant context from your existing codebase. The more context you provide, the better the generated code will integrate with your project.