> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cadcamfun.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Text to cad

# AI Text-to-CAD API

The AI Text-to-CAD API allows you to convert natural language descriptions into 3D CAD models. This powerful feature leverages advanced AI technology to interpret textual descriptions and generate corresponding parametric models.

## Overview

The Text-to-CAD functionality is implemented through a set of integrated services that handle different aspects of the process:

1. **Text Processing**: Analyzes natural language input to extract parameters, constraints, and design intent
2. **AI Model Processing**: Uses AI models to interpret the text and determine geometric requirements
3. **Model Generation**: Creates a parametric 3D model based on the interpreted specifications
4. **Parameter Extraction**: Identifies and extracts key parameters for later modification

## Key Components

The Text-to-CAD API consists of several key components:

* **AI Service**: Core service for text processing and model generation
* **AI CAD Service**: Specialized service for CAD-specific operations
* **AI Design Service**: Handles design-specific interpretation and analysis
* **Unified AI Service**: Coordinates between different AI services and models

## Basic Usage

### Generating a Model from Text

```typescript theme={null}
import { aiCadService } from '@/lib/aiCadService';

async function generateModelFromText(textDescription: string) {
  try {
    // Generate a CAD model from text description
    const result = await aiCadService.generateModelFromText({
      text: textDescription,
      format: 'model', // Return a model object rather than a file
      options: {
        resolution: 'high',
        units: 'mm',
      }
    });

    // The result contains the generated model and associated data
    const { model, parameters } = result;
    
    return result;
  } catch (error) {
    console.error('Error generating model from text:', error);
    throw error;
  }
}

// Example usage
const model = await generateModelFromText(
  'Create a cylindrical container with a diameter of 10cm and height of 15cm with a wall thickness of 2mm'
);
```

### Processing Text Without Generating a Model

If you want to analyze text without generating a model (for example, to extract parameters first):

```typescript theme={null}
import { aiCadService } from '@/lib/aiCadService';

async function analyzeTextDescription(textDescription: string) {
  try {
    // Process the text description to extract parameters and intent
    const processedText = await aiCadService.processText({
      text: textDescription,
      options: {
        enhanceWithAI: true,
        extractParameters: true
      }
    });

    // Access the extracted information
    console.log('Extracted parameters:', processedText.parameters);
    console.log('Extracted constraints:', processedText.constraints);
    
    return processedText;
  } catch (error) {
    console.error('Error analyzing text description:', error);
    throw error;
  }
}
```

### Generating a Model with Custom Parameters

You can also provide custom parameters along with the text description:

```typescript theme={null}
import { aiCadService } from '@/lib/aiCadService';

async function generateModelWithParameters(textDescription: string, customParameters: Record<string, any>) {
  try {
    const result = await aiCadService.generateModelWithParameters({
      text: textDescription,
      parameters: customParameters,
      format: 'model',
      options: {
        resolution: 'high',
        units: 'mm'
      }
    });
    
    return result;
  } catch (error) {
    console.error('Error generating model with parameters:', error);
    throw error;
  }
}

// Example usage
const model = await generateModelWithParameters(
  'Create a cylindrical container',
  {
    diameter: { value: 15, unit: 'cm' },
    height: { value: 20, unit: 'cm' },
    wallThickness: { value: 0.3, unit: 'cm' }
  }
);
```

## Advanced Features

### Working with Design Intent

The AI system can extract design intent from textual descriptions, which can be useful for more complex models:

```typescript theme={null}
import { aiDesignService } from '@/lib/ai/aiDesignService';

async function extractDesignIntent(textDescription: string) {
  const designIntent = await aiDesignService.extractIntent(textDescription);
  
  console.log('Primary purpose:', designIntent.purpose);
  console.log('Key features:', designIntent.keyFeatures);
  console.log('Design constraints:', designIntent.constraints);
  
  return designIntent;
}
```

### Model Refinement

After generating an initial model, you can refine it with additional text instructions:

```typescript theme={null}
import { aiCadService } from '@/lib/aiCadService';

async function refineModelWithText(modelId: string, refinementText: string) {
  try {
    const refinedModel = await aiCadService.refineModel({
      modelId,
      refinementText,
      options: {
        preserveOriginalParameters: true,
        prioritizeNewInstructions: true
      }
    });
    
    return refinedModel;
  } catch (error) {
    console.error('Error refining model:', error);
    throw error;
  }
}

// Example usage
const refinedModel = await refineModelWithText(
  'model_123456',
  'Add a threaded lid to the container'
);
```

### Batch Processing

For processing multiple text descriptions at once:

```typescript theme={null}
import { aiCadService } from '@/lib/aiCadService';

async function batchGenerateModels(textDescriptions: string[]) {
  try {
    const results = await aiCadService.batchGenerateModels({
      textDescriptions,
      format: 'model',
      options: {
        resolution: 'medium',
        units: 'mm'
      }
    });
    
    return results;
  } catch (error) {
    console.error('Error in batch generation:', error);
    throw error;
  }
}
```

## Configuration Options

The Text-to-CAD API provides several configuration options to control the generation process:

### Resolution Options

Control the level of detail in generated models:

```typescript theme={null}
{
  resolution: 'low' | 'medium' | 'high' | 'ultra'
}
```

### Unit Options

Specify the default units for generated models:

```typescript theme={null}
{
  units: 'mm' | 'cm' | 'm' | 'in' | 'ft'
}
```

### AI Enhancement Options

Control the level of AI enhancement applied to text descriptions:

```typescript theme={null}
{
  enhanceWithAI: boolean,  // Whether to apply AI enhancement
  enhancementLevel: 'basic' | 'standard' | 'advanced',
  preserveOriginalIntent: boolean,  // Whether to strictly adhere to original text
}
```

### Output Format Options

Control the output format of generated models:

```typescript theme={null}
{
  format: 'model',  // Return a model object
  format: 'stl',    // Return an STL file
  format: 'obj',    // Return an OBJ file
  format: 'step',   // Return a STEP file
}
```

## Parameter Reference

The Text-to-CAD system can extract and process many types of parameters from text descriptions:

### Dimensional Parameters

* `width`, `length`, `height`, `depth`: Basic dimensional parameters
* `diameter`, `radius`: Circular dimensions
* `thickness`: Material thickness
* `angle`: Angular measurements
* `distance`: Distances between features

### Material Parameters

* `material`: Type of material (e.g., "wood", "metal", "plastic")
* `density`: Material density
* `color`: Color specification

### Feature Parameters

* `cornerRadius`: Radius for rounded corners
* `holeRadius`, `holeDiameter`: Dimensions for holes
* `threadPitch`, `threadDiameter`: Parameters for threaded features
* `wallThickness`: Thickness of walls in hollow objects

### Constraint Parameters

* `parallel`, `perpendicular`: Orientation constraints
* `concentric`, `coaxial`: Alignment constraints
* `symmetric`: Symmetry constraints

## Error Handling

The Text-to-CAD API uses a consistent error handling mechanism:

```typescript theme={null}
try {
  const result = await aiCadService.generateModelFromText({
    text: 'Create a cube with 10cm sides',
    format: 'model'
  });
} catch (error) {
  if (error.code === 'TEXT_PROCESSING_ERROR') {
    console.error('Error processing text:', error.message);
    // Handle text processing errors
  } else if (error.code === 'MODEL_GENERATION_ERROR') {
    console.error('Error generating model:', error.message);
    // Handle model generation errors
  } else if (error.code === 'PARAMETER_EXTRACTION_ERROR') {
    console.error('Error extracting parameters:', error.message);
    // Handle parameter extraction errors
  } else {
    console.error('Unknown error:', error);
    // Handle other errors
  }
}
```

## Common Error Codes

| Error Code                   | Description                                           |
| ---------------------------- | ----------------------------------------------------- |
| `TEXT_PROCESSING_ERROR`      | Error processing or interpreting the text description |
| `MODEL_GENERATION_ERROR`     | Error generating the 3D model                         |
| `PARAMETER_EXTRACTION_ERROR` | Error extracting parameters from the text             |
| `VALIDATION_ERROR`           | Invalid input parameters or constraints               |
| `AI_SERVICE_ERROR`           | Error in the underlying AI service                    |
| `RESOURCE_LIMIT_EXCEEDED`    | Exceeded resource limits (e.g., complexity, size)     |

## Events

The Text-to-CAD system triggers several events that you can subscribe to:

```typescript theme={null}
import { events } from '@/lib/utils/events';

// Listen for text processing events
events.subscribe('textToCad.processingStarted', (data) => {
  console.log('Text processing started:', data.text);
});

events.subscribe('textToCad.processingCompleted', (data) => {
  console.log('Text processing completed:', data.processedText);
});

// Listen for model generation events
events.subscribe('textToCad.generationStarted', (data) => {
  console.log('Model generation started for:', data.text);
});

events.subscribe('textToCad.generationProgress', (data) => {
  console.log(`Generation progress: ${data.progress}%`);
});

events.subscribe('textToCad.generationCompleted', (data) => {
  console.log('Model generation completed:', data.model);
});
```

## Best Practices

### Writing Effective Text Descriptions

To get the best results from the Text-to-CAD system, follow these guidelines:

1. **Be Specific**: Include precise measurements and units
2. **Use Clear Terminology**: Use common geometric terms (cube, cylinder, etc.)
3. **Specify Relationships**: Clearly describe how parts relate to each other
4. **Include Purpose**: Mentioning the purpose helps the AI understand intent
5. **Start Simple**: Begin with basic shapes and add complexity incrementally

### Performance Optimization

* **Pre-process Text**: For complex descriptions, consider breaking them down
* **Cache Results**: Store processed text results if they'll be reused
* **Use Appropriate Resolution**: Only use high resolution when needed
* **Batch Process**: Use batch API for multiple related generations

### Integration Patterns

* **Two-Stage Processing**: Process text first to extract parameters, then confirm with user before generating
* **Progressive Enhancement**: Start with basic model and refine with additional text instructions
* **Hybrid Approach**: Combine text generation with manual CAD operations for complex models

## Examples

### Basic Shape Generation

```typescript theme={null}
const cubeModel = await aiCadService.generateModelFromText({
  text: 'Create a cube with 10cm sides',
  format: 'model'
});

const cylinderModel = await aiCadService.generateModelFromText({
  text: 'Make a cylinder with 5cm diameter and 12cm height',
  format: 'model'
});
```

### Complex Object Generation

```typescript theme={null}
const cupModel = await aiCadService.generateModelFromText({
  text: 'Design a cup with a cylindrical body (8cm diameter, 10cm height) with a handle on the side',
  format: 'model'
});

const boxModel = await aiCadService.generateModelFromText({
  text: 'Create a rectangular box (10cm×5cm×3cm) with rounded corners (1cm radius) and a hinged lid',
  format: 'model'
});
```

### Mechanical Parts Generation

```typescript theme={null}
const bracketModel = await aiCadService.generateModelFromText({
  text: 'Design a mounting bracket with a 10cm×5cm base plate (3mm thick) and two mounting flanges on the long sides (each 3cm high, with 5mm holes centered 1cm from the top)',
  format: 'model'
});
```

## Troubleshooting

### Common Issues and Solutions

#### Model Not Generated as Expected

* Be more specific about dimensions and shapes
* Check that your description doesn't contain ambiguous terms
* Try breaking down complex designs into simpler components

#### Missing Details

* Explicitly specify all critical dimensions
* Mention specific features like holes, fillets, or chamfers
* Reference the purpose or function of the model

#### System Not Recognizing Terms

* Use common geometric terminology
* Specify precise measurements with units
* Avoid industry-specific jargon

## API Reference

### aiCadService

| Method                          | Description                                     |
| ------------------------------- | ----------------------------------------------- |
| `processText()`                 | Process and analyze text description            |
| `generateModelFromText()`       | Generate a 3D model from text description       |
| `generateModelWithParameters()` | Generate a model with specific parameters       |
| `refineModel()`                 | Refine an existing model with additional text   |
| `batchGenerateModels()`         | Generate multiple models from text descriptions |

### aiDesignService

| Method                  | Description                                 |
| ----------------------- | ------------------------------------------- |
| `extractIntent()`       | Extract design intent from text description |
| `analyzeDesign()`       | Analyze design complexity and feasibility   |
| `suggestImprovements()` | Suggest improvements to a design            |

For complete API reference including all parameters and return types, see the [Text-to-CAD API Reference](./reference/text-to-cad.md).
